Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 985 of the free egghead.io lessons, plus get CSS content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Target empty elements using the :empty pseudo-class

0:58 CSS lesson by

You can target an element that has no child elements by using the :empty pseudo-class. With browser support down to IE9, it's solid, easy way to select empty elements without any additional markup.

Be aware that whitespace is considered a "child", so :empty will not work if the element has no children, but has space between the opening and closing tags.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

You can target an element that has no child elements by using the :empty pseudo-class. With browser support down to IE9, it's solid, easy way to select empty elements without any additional markup.

Be aware that whitespace is considered a "child", so :empty will not work if the element has no children, but has space between the opening and closing tags.

Avatar
Codilime

Not applying css to :empty elements is not equal to setting 'display: none' to :empty elements.

In reply to egghead.io
Avatar
Nut

Usually egghead courses have great sound. But this and also Prof. Frisby's are absolutely awful. What is wrong with that?

I've set up some HTML to display a notification bar. I've also added some basic styles to add border, margin, and padding. If I add an empty notification bar using the div class of Alert, you'll see that the notification bar renders with margin, background-color, and padding and all of this.

Result

Using the empty pseudo-class we can target the Alert notification bar by saying .Alert:empty { Inside of that CSS block just say display: none; and you'll see that the empty notification bar disappears.

Empty Bar Removed

Instead of targeting the Alert class twice, we can chain multiple pseudo-classes together. I'll comment this block. I'll comment this block.

style.css

/* .Alert:empty {
    display: none; 
} */

I'll come back to the original block. I can say :not and then inside of the not selector, say :empty This way, any element with the class of Alert that is not empty will receive these following styles.

style.css

.Alert:not(:empty) {
    border: 3px solid darkgreen;
    margin: 1em;
    padding: 1em;
    background-color: seagreen;
    color: white;
    border-radius: 4px;
}
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?