CSS :empty Selector

Samantha Ming
4 min readAug 5, 2019
CodeTidbit by SamanthaMing.com

Often, we want to style elements that contain content. How about when an element has no children or text at all? Easy, you can use the :empty selector 🤩

<p> </p><!-- NOT empty: note the blank space -->
<p></p><!-- YES empty: nothing inbetween -->
p::before {
font-family: "FontAwesome";
content: "\f240";
}
p:empty::before {
content: "\f244";
}

p {
color: silver;
}
p:empty {
color: red;
}

What’s considered empty?

When I first encounter this, there was a few confusion about what this property considers as empty. Let’s stick with MDN’s definition here:

The :empty CSS pseudo-class represents any element that has no children. Children can be either element nodes or text (including whitespace). Comments, processing instructions, and CSS content do not affect whether an element is considered empty.

Is empty

As long as there is no whitespace, it’s an empty element.

<p></p>

Comment in between is also considered an empty element. As long as there is no whitespace.

<p><!-- comment --></p>

Not empty

--

--

Samantha Ming

Frontend Developer sharing weekly JS, HTML, CSS code tidbits🔥 Discover them all on samanthaming.com 💛