Seriously? Are we talking of nothingness here? No, we're talking about "emptiness" instead! Just a couple of details that are worth knowing, some about good practices, others about code correctness.
What are self-closing and empty tags?
HTML elements that do not have closing tags such as <br>
, <hr>
, and <img>
are considered self-closing tags. These types of elements cannot contain other elements or content.
Container tags are elements such as divs or spans that have an opening tag (<div>
) and a closing tag (</div>
), and they are used to contain other elements or content. A container element is considered empty if it does not contain any other elements, text or whitespace such as spaces or line-breaks. HTML comments, processing instructions, and CSS-generated content with the ':before' and ':after' pseudo-classes do not affect whether an element is empty.
HTML Self-closing tags
According to the HTML5 specification, there are 15 self-closing tags. These are also known as self-closing or void tags because they do not have a corresponding closing tag and they cannot contain other elements.
<area>
<base>
<br>
<col>
<embed>
<hr>
<img>
<input>
<keygen>
<link>
<meta>
<param>
<source>
<track>
<wbr>
The closing slash dilemma
According to the WC3 HTML5 spec, closing slashes for empty tags such in <br/> or <br /> are optional (closing slashes are required only for XHTMLs and XMLs), as is the space before the slash, so I often tend to avoid using them, just to save some kb. As always, the important thing is that you do what you do consciously!
Adding a closing tag to an empty tag such as <br></br>
or <input type="text"></input>
is simply considered invalid HTML.
Are empty divs bad practice?
Not necessarily. Empty divs (or any other container element) are only considered bad practice if they serve no purpose. But "doing things without reason and logic" when coding, is a bad practice itself... Empty tags are valid HTML and they have potentially many uses such as spacer elements, design elements, and placeholders for JavaScript actions.
Bonus tips
Tip #1: select empty tags In CSS
Did you know that you can select empty tags in CSS with the :empty
pseudo-class? Keep in mind that tags are only empty if they contain no whitespace or other elements. HTML comments, processing instructions, and CSS-generated content with the :before
and :after
pseudo-classes do not affect whether an element is empty.
Tip #2: empty elements in JavaScript
To determine if an element is empty, check the length
of the childNodes
property. Since this property returns a NodeList
of the element's children (including text nodes, comments, and other elements), if you end up having 0 (zero), it means the element is empty. Self-closing tags such as <br>
or <img>
are always empty.
To empty an HTML element, instead, set its innerHTML
property to an empty string or loop through an element's childNodes
removing them one by one with the removeChild()
function.