Target empty elements using the :empty pseudo-class

Damon Bauer
InstructorDamon Bauer
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 years ago

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.

[00:00] 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.

[00:19] Using the empty pseudo-class we can target the alert notification bar by saying "alert and empty." Inside of that CSS block just say "display none," and you'll see that the empty notification bar disappears.

[00:37] Instead of targeting the alert class twice, we can chain multiple pseudo-classes together. I'll comment this block. I'll comment this block. 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.

Andreas Klein
Andreas Klein
~ 7 years ago

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

Daniel Yim
Daniel Yim
~ 6 years ago

Agreed. The sound quality is awful on this course.

Markdown supported.
Become a member to join the discussionEnroll Today