01
Mar '15

This will be a very short post but I’ve just discovered my favourite feature of CSS3 and I wanted to share in case any of you out there missed it. Ever find yourself with elements that, if populated, work really well in the page and give a lovely user experience but, if empty, just leave gaping holes in the page. I particularly get this situation with message bars in page headers, or in labels I create ready to receive validation error messages.

Now I know the true CSS ninjas will have a million and one ways to deal with this, but by far the simplest and most excellent approach I’ve found is the CSS3 :empty selector:

label.error:empty {
   display: none;
}

Just like that! Any empty labels with the ‘error’ class will be hidden. As soon as they are populated they will show. Easy.
It’s worth noting though that even a single space within the element will cause it to be viewed as not empty – be careful with your whitespace out there!

<Insert note about CSS3 not being supported by all browsers here>