There is no self-closing tag in html

 
 
  • Gérald Barré

There is no self-closing tag in html! This statement seems wrong as you may have seen self-closing tags in html, such as <img src="foo.jpg" /> (with /> at the end). However, this is not a concept in html. Let me explain.

While HTML looks similar to a permissive XML, it's not XML. As an example, you don't need to open or close all tags. For instance, you can omit the closing tag for some elements such as <li>, <td>, <tr>, etc. You can also omit opening tags such as <html>, <head>, or <body> tags in some situations. The browser will add them automatically. Note that this is well-defined in the specification: Optional tags.

There are 6 types of elements in html. The most common ones are normal elements and void elements. A void element is an element whose content model never allows it to have contents under any circumstances. Also, void elements can't have an end tag. For instance, the <img> or <br> tags are void elements. From the specification: On void elements, the / before > does not mark the start tag as self-closing but instead is unnecessary and has no effect of any kind. This means <br> and <br /> are equivalent.

For non void elements, the parser also skips the / before > and considers the tag as a normal tag. Only a closing tag will close the element.

Let's consider the following html fragment:

HTML
<div />a
<div>b</div>

The parser will create the following DOM:

HTML
<div>a
    <div>b</div>
</div>

You can see that the first <div /> is not a self-closing tag. It's a normal tag. The browser will ignore the / and consider the tag as a normal tag. The first <div> element is closed implicitly at the end of the document.

Here's an example for a void element:

HTML
<br>
<br />
<br></br>

The parser will create the following DOM:

HTML
<br>
<br>
<br>
<br>

Note that while self-closing tag is not a concept in html, it has its importance in SVG or MathML elements (Foreign elements). An <svg> element must contain a valid XML document. Therefore, you must use self-closing tags in SVG.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub