There is no self-closing tag in html

 
 
  • Gérald Barré

There is no self-closing tag in HTML! This may seem wrong, since you have likely seen syntax like <img src="foo.jpg" /> (with /> at the end). However, self-closing tags are not a concept in HTML.

While HTML looks similar to XML, it is not XML. For example, you do not need to open or close all tags. You can omit closing tags for elements like <li>, <td>, <tr>, and others. You can also omit opening tags such as <html>, <head>, or <body> in some situations, and the browser will add them automatically. This behavior is well-defined in the specification: Optional tags.

There are 6 types of elements in HTML. The most common are normal elements and void elements. A void element is one whose content model never allows it to have contents. Void elements also cannot have an end tag. For example, <img> and <br> are void elements. According to the specification, on void elements the / before > does not mark the start tag as self-closing; it is unnecessary and has no effect. This means <br> and <br /> are equivalent.

For non-void elements, the parser also skips the / before > and treats the tag as a normal opening tag. Only an explicit 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>

The first <div /> is not a self-closing tag; it is treated as a normal opening tag. The browser ignores the /, and 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>

While self-closing tags are not a concept in HTML, they do matter in SVG and MathML elements (foreign elements). An <svg> element must contain a valid XML document, so self-closing tags are required within SVG.

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

Follow me:
Enjoy this blog?