I’m in love with the simplicity that CSS3 selectors can bring to our stylesheets. Here’s a brief explanation of one of my favourites: the :empty
pseudo-class.
What is the :empty
pseudo-class
Here is the definition taken from the W3C Selectors Level 3 specification:
The
:empty
pseudo-class represents an element that has no children at all.
Seems easy enough, right? That’s because it is. The :empty
pseudo-class is going to target elements that are completely empty; for example, an empty paragraph:
<p></p>
Or an empty table cell:
<table> <tr> <td></td> </tr> </table>
It won’t target this paragraph though (there is a space within the p
tag, therefore it isn’t empty):
<p> </p>
A practical example
So when can this selector be useful?
Image you’re styling a table and some of the data cells have no content — you can style them differently using the magic :empty
pseudo-class.
Let’s take the table I’ve created for the Adding Style with CSS: A Beautiful Table article. I’m going to use the same CSS, but change the data to make it simpler (the data I’ve added makes no sense, but you get the point…). I’m also going to remove the content in a few cells, to make this example relevant.
So this is our markup:
<table> <caption>A simple table</caption> <thead> <tr> <th scope="col" rowspan="2">Some headings</th> <th scope="col" colspan="4">More headings</th> </tr> <tr> <th scope="col">Great</th> <th scope="col">Brilliant</th> <th scope="col">Genius</th> <th scope="col">Good</th> </tr> </thead> <tfoot> <tr> <th scope="row">Interesting totals</th> <td>155</td> <td>165</td> <td>70</td> <td>140</td> </tr> </tfoot> <tbody> <tr> <th scope="row">Curious</th> <td>5</td> <td>35</td> <td>50</td> <td>15</td> </tr> <tr> <th scope="row">Awesome</th> <td>75</td> <td>90</td> <td></td> <td>5</td> </tr> <tr> <th scope="row">Fabulous</th> <td>30</td> <td></td> <td>20</td> <td>80</td> </tr> <tr> <th scope="row">Nice</th> <td>45</td> <td>40</td> <td></td> <td>40</td> </tr> </tbody> </table>
This is what I’m going to add to the CSS:
tbody td:empty { background: #EFEFEF; }
And now the empty cells are styled differently! I don’t think this could have been much easier.
Also, if you really need to ask, this selector works on the latest versions of Firefox, Safari, Chrome and Opera. It will probably work on Internet Explorer 9, like most CSS3 selectors will. (The first person to point out the obvious, will be directed to this link. — Thanks, Jack, for helping me remember the link!)
Here’s the example:
So, will you be using this selector any time soon?