DEV Community

Cover image for How to write semantic HTML
Max Rozen
Max Rozen

Posted on • Updated on • Originally published at maxrozen.com

How to write semantic HTML

What does "semantic" mean?

To write semantic HTML is to give it meaning, rather than just describing how it should look in the browser.

Take this code snippet for example:

<div class="heading">My Heading</div>
<div class="paragraph">Here's a sentence I wrote just for you.</div>
Enter fullscreen mode Exit fullscreen mode

While it is possible to write CSS to make your heading and paragraph classes appear as you like, software tooling that reads your markup has no idea what it means. It'll just see text within a div, and not know how the text in the first div relates to the second div.

Here's the semantic way of writing the previous example:

<h1>My Heading</h1>
<p>Here's a sentence I wrote just for you.</p>
Enter fullscreen mode Exit fullscreen mode

The advantages of writing your HTML semantically are:

  • You get a set of default styles for free (which you can override with CSS if you wish)
  • Communication: Developers who read your code in the future instantly know what was intended - there is no ambiguity to semantic markup
  • SEO: Search engines like Google look for <h1> tags to determine which keywords to associate your content with
  • Screen readers can now read your content as you intended

More examples of Semantic vs Non-semantic markup

Buttons

Good:

<button>Click me</button>
Enter fullscreen mode Exit fullscreen mode

Bad:

<div>Click me</div>
Enter fullscreen mode Exit fullscreen mode

Why is this bad?

Divs are not focusable by keyboards. We could make them focusable by adding tabindex="0", but this can still be hacky in the case of inputs.

Inputs

Good:

<input type="checkbox" />
Enter fullscreen mode Exit fullscreen mode

Bad:

<div role="checkbox"></div>
Enter fullscreen mode Exit fullscreen mode

Why is this bad?

As mentioned before, divs are not focusable by default. Adding tabindex="0" here will make your div focusable, but then you would also need to write additional JavaScript to submit the value of your "checkbox" when the rest of the form submits.

Shameless plug

If you'd like more tips on how to improve your frontend, you can follow me on Twitter or subscribe to my newsletter as I regularly post articles there.

Top comments (4)

Collapse
 
orifmilod profile image
Orif Milod • Edited

I think you missed some important parts of writing semantic HTML. A lot of people make a mistake by using div to wrapping everything. Tags that most people miss are main header footer section etc. Using these tags can help in better SEO.

Collapse
 
thinkverse profile image
Kim Hallberg

Don't forget the useful article, and aside as well.

Collapse
 
rozenmd profile image
Max Rozen

Thanks.

Collapse
 
bayuangora profile image
Bayu Angora • Edited

Which one is better for header and footer menu? With div or button?