Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

Here's a fun one: consider the following HTML in which the classes red, blue and green render the particular background color โ€” what will be rendered?

<div class="blue" />
  Blue
  <div class="red" />
    Red
    <div class="green" />
      Green
    </div>
  </div>
</div>

Well... did you see the self-closing divs? That's tricky, right? Have a look at it below. ๐Ÿ‘‡

HTML
CSS
Preview

๐Ÿคฏ Jake Archibald published a real banger getting into the argument of self-closing HTML elements, and it's more than worth a read.

Here's the tl;dr!

Self-closing elements are mostly a relict from the XHTML era. XHTML was this unforgiving friend who made a massive scene about everything. It required developers to write 100% correct markup. Not cool โ€” we all make mistakes, right?

HTML, on the other hand, is your friendly pal that tries to make the best out of what you throw at it โ€” even when you mess up and write invalid HTML.

And it's funny that whenever you close an hr, br or input element (so-called void elements), the / has no effect whatsoever!

Here's the WHATWG spec describing start tags of void elements:

On void elements, it [/] does not mark the start tag as self-closing but instead is unnecessary and has no effect of any kind.

Can that be real? If you head over to the W3C HTML validator, you get the following result for self-closed elements:

HTML validator result showing errors and infos about self-closing tags.

If you self-close HTML elements, you either write invalid HTML and the browser will treat it as an open tag or it has purposefully no effect on void elements.

But be aware that SVG, XML and MathML in HTML are exceptions, and do have self-closing tags.

As always, HTML just makes the best of everything. The tag name is the only thing that matters for the HTML parser to evaluate if an element is void and "self-contained".

If you're curious; here are the defined void elements, area, base, br, col, embed, hr, img, input, link,meta, source, track, and wbr.

So, when you look at the HTML at the beginning of this article, the closed divs (<div />) have no effect whatsoever. It's three nested divs, and the browser closes the elements when it discovers the matching closing tag (</div>).

Wild!

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 16 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles