How to Only Style Elements Without Content Using CSS

How to Only Style Elements Without Content Using CSS

Adding styles for an HTML element that's on-screen is easy. Not styling an element that's not on screen is even easier. But, what if the element is always on-screen and you want to hide it or only style it when it contains content? In this article, you'll learn how to only style elements without content using CSS.

Manipulating contentless elements is useful for hiding empty elements, fixing elements with extraneous styling – like empty divs with padding – and for targeting empty table cells like the top left table-cell in a data chart or a header-cell over a call-to-action column that doesn't use a label.

  • Hide empty elements
  • Re-style empty elements
  • Target empty elements with CSS or JS

:empty CSS Selector

Using the CSS selector :empty, you can target HTML elements that don't contain content – i.e. they're empty.

Here's how :empty works in CSS.

div:empty {
	display: none;

You can use it much the same way to target empty elements in JavaScript, too. Here's an example using jQuery:


:empty can be extremely useful in a tricky situation, 

:empty Flaws

:empty is not always perfect. Sometimes it can be difficult to target a visually empty element if it's not completely empty – for example, :empty fails when an element contains whitespace of any kind.

This works with :empty

<div><!-- no whitespace here --></div>

This does not work with :empty

<div>    </div><!-- doesn't work, see that whitespace? -->



</div><!-- nope, not going to work -->

This doesn't work either

<!-- there is whitespace above and below... -->

:blank CSS Selector

An even better alternative to :empty is :blank.

:blank does what empty does except it also targets elements with whitespace and comments, so it's better. The only problem with :blank is that it has no browser support, so you can't actually use it yet.