← Back to context

Comment by onion2k

14 hours ago

In the case of <br/> and <img/> browsers will never use the content inside of the tag, so using a closing tag doesn't make sense. The slash makes it much clearer though, so missing it out is silly.

"Self-closing tags" are not a thing in HTML5. From the HTML standard:

> On void elements, [the trailing slash] does not mark the start tag as self-closing but instead is unnecessary and has no effect of any kind. For such void elements, it should be used only with caution — especially since, if directly preceded by an unquoted attribute value, it becomes part of the attribute value rather than being discarded by the parser.

It was mainly added to HTML5 to make it easier to convert XHTML pages to HTML5. IMO using the trailing slash in new pages is a mistake. It makes it appear as though the slash is what closes the element when in reality it does nothing and the element is self-closing because it's part of a hardcoded set of void elements. See here for more information: https://github.com/validator/validator/wiki/Markup-%C2%BB-Vo...

  • It's not a mistake if you want to be able to use XML tools on your HTML. It's basically no effort to make HTML also be valid XML so you'd might as well get the additional tooling compatibility and simplicity for free. For the same reason, it's courteous toward others.

Self-closing tags do nothing in HTML though. They are ignored. And in some cases, adding them obfuscates how browser’s will actually interpret the markup, or introduce subtle differences between HTML and JSX, for example.

How does the slash make it clearer? It's totally inert, so if you try to do the same thing with a non-void tag the results will not be what you expect!

  • It indicates that the content that follows is not inside of the tag without the reader needing to remember how HTML works. Tags should have either a self-closing slash, or a closing tag.

    The third way of a bare tag is where the confusion comes from.

    • It doesn't indicate that, though. If you write <div />, for example, the content that follows is inside of the tag. So the reader still needs to remember how HTML works, because the slash does nothing.

      1 reply →