This blog will teach you:
What are Self-Closing Tags in HTML?
In HTML, several tags consist of opening and closing tags, such as <h1>, <div>, <li>, and many more. However, the links and images cannot contain content because they are pointers to elements on the website.
In modern HTML versions such as XHTML, developers use a self-closing tag that includes a “/” within the carets(<>). For instance:
Analyze the above code, the <img> element does not contain a closing tag.
Output
How to Write Self-Closing Tags?
In HTML, a self-closing tag does not need to be closed manually by utilizing the closing tag i.e., it does not need a closing tag as </img>.
To write a self-closing tag, do the following:
- First, add the “<” character.
- Specify the element name.
- Add optional attributes.
- More than one space character is optional.
- A “/” character, only if the element is a void element.
- At last, a “>” character.
Examples: <br/>, <hr/>
Note: Self-closing tags are also known as “empty tags”. These must not contain a separate closing tag like </br> or </hr>. The browser will generate an error if separate closing tags are mentioned for the empty elements.
List of Self-Closing Tags
Here is the list of void tags:
- <br>
- <hr>
- <param>
- <col>
- <base>
- <img>
- <command>
- <link>
- <wbr>
- <keygen>
- <embed>
- <source>
- <area>
- <input>
- <track>
- <meta>
Let’s perform some examples to see how these tags are mentioned in the HTML.
Example 1: How to Use the <input> HTML Tag?
In HTML, first, add a label element starting with the tag <label>. Add a caption and then add an input element, which is a self-closing element and it does not have a separate ending tag:
Output
Example 2: How to Use the <br> HTML Tag?
As we have discussed, the self-closing tags can be written as <.. />. Let’s include the slash in the <br> tag in the below example:
Output
Is the Ending Slash Required?
To get the answer to the stated question, check out the given table:
XHTML | Required |
HTML4 | Technically invalid but accepted by W3C’s HTML validator. |
HTML5 | Optional |
In SVG, XHTML, and XML, all the tags can be self-closed by the closing slash.
Conclusion
The self-closing tags are also called void elements, singleton tags, or empty tags. In HTML, the empty tags must not have separate ending tags. However, in SVG, XHTML, and XML, any element can have a slash at the end of the starting tag. This article has explained the allowed ways to close self-closing tags for void elements with examples.