HTML Introduction | Getting Started with HTML | HTML Self-Closing Tags

Self-closing is syntax originally used in XHTML, where an element must close itself with a slash.

Some tags do not require a closing tag. For example, the img tag is as follows.

<img src="my_image.jpg" alt="My image" width="100" height="100" />

There is no </img> here.

The full list of self-closing tags in HTML5 is as follows. In the HTML specification, these are called “void elements.”

<area />
<base />
<br />
<col />
<command />
<embed />
<hr />
<img />
<input />
<keygen />
<link />
<menuitem />
<meta />
<param />
<source />
<track />
<wbr />

The space before the slash is optional.

Is the ending slash optional?

  • HTML5: The slash is optional.
  • HTML4: The slash is technically invalid. However, it is accepted by the W3C HTML validator.
  • XHTML: The slash is required.

It is better to always add the slash, because it provides a visual cue for non-closing tags.

XHTML supports self-closing syntax for all tags.

In XML and XHTML, every tag closes itself with an ending slash, <... />.

When testing XML, make sure the server is sending the correct internet media type as XHTML, for example application/xhtml+xml. Otherwise, regardless of the file’s DOCTYPE, the browser treats it as HTML.

References

https://www.w3.org/TR/html/syntax.html#void-elements