The <div> and <span> elements are two really popular ones in HTML. Generic building blocks without any meanings.
If we want to build a better and more accessible site or app we need to use the semantically correct elements for each section/block. With HTML5 we got a lot of new tags which is a blessing, but life isn’t this simple.
The web is more complicated each day, and we need meaningless elements for building results as we want. The <div> and <span> elements are like the most generic Lego building blocks; we need them but nothing more.
What is the Difference?
The <div> element is a block-based element which fills the space horizontally (brake the line before and after it) and mostly used for grouping other items.
The <span> element is an inline item which is used in other inline things (usually text) to mark a specific section.
Of course, we can modify both display property, but mostly, we use the default values by convention.
When to Use Them?
If you have to build a non-semantic section – like a layout or something which you want to target with JS code by a class or id – you have to use them.
If your project has some grid framework you have to use a lot of <div> element for build desired structure, and this is alright. The one thing which is essential here that you also have to use correctly the fundamental layout elements like <header>, <footer>, <main>, <aside> if you want a more accessible layout.
<div class="container"> <div class="row"> <main class="col-12 col-md-8"> Your main content... </main> <aside class="col-12 col-md-4"> Your sidebar content... </aside> </div> </div>
Combining semantic and non-semantic elements is the base of HTML, and it is a good point if you have fewer tags, but sometimes we can’t avoid the bloat.
<p>This is a <strong>highlighted text</strong> which has meaning.</p> <p>This is a <span class="bold">highlighted text</span> which hasn't meaning.</p>
Don’t use span to make generic text formatting like bold or emphasize use <strong> and <em> tag; these tags have meaning.
Need a web developer? Maybe we can help, get in touch!