As frontend developers, we tend to focus on using our choice of framework/library correctly, and we spend far less time deciding if a div
should be used instead of a section
tag and vice-versa in our HTML or JSX.
But in reality, semantics needs to be followed in order to make sure that our HTML elements can be read and understood at a glance.
The whole idea of writing readable and meaningful HTML is a journey into writing Semantic HTML, i.e. HTML elements that are self-descriptive even without a class name attached to them. The English dictionary describes the word, Semantic as relating to meaning in language or logic.
Benefits of using Semantic Elements
According to W3C: "A semantic Web allows data to be shared and reused across applications, enterprises, and communities."
It helps to make your pages accessible for the visually impaired as screen readers can easily identify what each element is meant to present.
It helps to improve a page's search rankings as it's easy for search engines to consider its contents as important keywords.
During code reviews, finding blocks of meaningful code is significantly easier than searching through
div
s with or without namespaced classes.
Note: HTML should be coded to represent the data that will be populated, and using semantic elements does exactly that, it does not replace CSS styling.
Semantic Elements
There are about 100 semantic elements available, but in this article, I will use a few in composing a simple web page, the same page will be composed without the use of semantic HTML in order to run a comparison between the two based on the benefits highlighted above.
HTML without semantic elements
<div class='text-section'>
<h2>The title of the page</h2>
<div class='main-article'>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<p class='side-text'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit...
</p>
</div>
<div class='image-section'>
<img src='/media/an-image-somewhere.jpg' alt='the main image'>
<p class='image-caption'>The main picture in this page</p>
</div>
</div>
HTML with semantic elements
<section class='text-section'>
<h2>The title of the page</h2>
<article class='main-article'>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<aside class='side-text'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit...
</aside>
</article>
<figure class='image-section'>
<img src='/media/an-image-somewhere.jpg' alt='the main image'>
<figcaption>The main picture in this page</figcaption>
</figure>
</section>
Looking at the two blocks of code above, you'll agree with me that while they represent the same pages, the second one is providing more context into what to expect on the webpage than the first one.
If you find this article insightful, please react, comment, and share.