Grow your CSS skills. Land your dream job.

:empty

Last updated on:

The :empty pseudo selector will select elements that contain either nothing or only an HTML comment.

div:empty {
   display: none;
}

Will Match

<div></div>

<div><!-- test --></div>

Will Not Match

<div> </div>

<div>
  <!-- test -->
</div>

<div>
</div>

It's useful for hiding empty elements that might cause weird spacing (e.g. they have padding). Or something like removing the border from the top left table cell element in a cross-referencing table.

Other Resources

Browser Support

Chrome Safari Firefox Opera IE Android iOS
any 3.1+ 1.5+ 9.5+ 9+ ? ?

Comments

  1. Henry
    Permalink to comment#

    Loving the :empty pseudo selector – is especially good with BuddyPress template notices!

  2. Charles Walton
    Permalink to comment#

    For reference, puesdoelements (:after/:before) don’t count as content. Check it:

    http://jsbin.com/OveLetU/4/edit?html,css,output

  3. What about that css:

    *:empty {
        display:none;
        margin:0;
        padding:0;
        border:0;
    }
    
    • Yeah, it’s gonna work. Might wanna use !important there as well.

      One useful example would be if you have hard-coded elements.
      You can use
      div:empty+hr,
      p:empty+hr {
      display: none
      }

      That would hide unneeded separators.
      Tweak to your own preference.

  4. Permalink to comment#

    *:empty rule style even hr tag and <a>img tag</a>

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".