How to Only Style Elements Without Content Using CSS

by | March 30, 2021 | CSS, Website Development

This page may contain affiliate links to recommended products or services. If you choose to purchase after clicking a link, I may receive a commission at no additional cost to you.

Last updated on: February 8, 2023

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:

$('div:empty').hide();

: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></div>
<div><!-- no whitespace here --></div>

This does not work with :empty

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

or

<div>

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

This doesn’t work either

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

: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.

Floyd Hartford is a website developer from southern Maine. He's focused on creating and building WordPress websites and loves spending time digging into code like HTML, CSS, scss, jQuery, PHP, and MySQL.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

15 + fifteen =

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Looking for WordPress Help?

I’m a freelance web developer specializing in small business and corporate marketing websites.

Pin It on Pinterest