Semantic HTML

One of the most important things your HTML should be, to benefit both people and machines - is for it to be semantic. Let's look at what means.

Semantics

I agree with the definition of semantics as the folks at Mozilla have written it:

Semantics refers to the meaning of a piece of code

This is important, if you want your code to look professional, have better readability and be more easily maintainable.

What does it mean for HTML to be semantic?

As they define further in the page, it's the difference of having code like this:

<h1>This is a top level heading</h1>

and not this:

<span style="font-size: 32px; margin: 21px 0;">Is this a top level heading?</span>

And to add another example, from this blog post:

Do this

<div id="container" class="container">
  <ul class="items">
    <li class="item item--1">Item 1</li>
    <li class="item item--2">Item 1</li>
    <li class="item item--3">Item 1</li>
  </ul>
</div>

Not this

<div id="container" class="container">
  <div class="item item--1">Item 1</div>
  <div class="item item--2">Item 1</div>
  <div class="item item--3">Item 1</div>
</div>

If it were up to me, I'd do this:

<div class="container">
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</div>

Which is:

  • Merge CSS properties into classes, dont use ids for styling
  • Have the least amount of classes on elements, for example by using more specific selectors - of the child elements, not each element individually

So the first thing that stands out is proper element usage. Of course you can use spans to define all text on your page, but you will pay by taking more time to understand what it actually means.

Instead, you should familiarize yourself with the available HTML elements and their usage.

Do machines care?

Naturally. They're built by people who care. Search engine developers care about data quality and if your page turns up as having no heading elements, it will send you to the bottom of search results fast. Very fast.

That's just thinking about the search engines, future technology relies on quality data, so the price of having skipped learning semantic HTML will only increase.

Accessibility

A very important factor, to ensure the universal availability of web pages, is also accessibility. To further explore the topics behind this, I will go into it in another post, but I thought it's important to also note here.

In short, imagine if you'd have to navigate your web page only with your keyboard. What's easier to navigate?

  • A structured hierarchy
  • A soup of <span> and <div> elements

It should be pretty obvious.

Semantic CSS and JS

CSS, JS and all other code languages have their own conventions on how to make the code you write more semantic.