CSS :not and :empty selectors to apply styles when an element is empty and not empty

Posted in HTML and CSS -

There may be times you need to apply a style if an element is empty, or if it is not empty. Use the :not & :empty selectors to do this, as shown in this post. They are supported by all modern browsers, and Internet Explorer from 9 and up.

tl;dr

Check out the example here or download the compressed version here.

Applying styles to an empty element

You can use :empty to apply styles to element that contains no content. For example:

<p class="test2"><!-- this contains no content other than an HTML comment --></p>

You can apply a style to this element if it contains no content like so:

.test2:empty {
    border: 1px solid blue;
}

This will put a blue border around the element. Note that because it contains no content, if the element has no padding then it will be more like a line than a bordered element, but it's just an example.

Note that being empty means there is no content at all, including white space.

Applying styles to an element that is not empty

You can also :not in conjunction with :empty to do the opposite: apply a style when the element is not empty. Consider the following two paragraphs:

<p class="test1">This element contains content</p>
<p class="test1"><!-- this contains no content other than an HTML comment --></p>

When the following style is applied, the first paragraph will have a red border and some padding, and the second paragraph with have no additional styling applied, unless it's been defined elsewhere:

.test1:not(:empty) {
    border: 1px solid red;
    padding: 10px;
}

Browser support

This has been tested with a <!doctype html> and has the following browser support, according to W3Schools (:not & :empty):

  • Chrome 4.0+
  • Firefox 3.5+
  • Internet Explorer 9.0+
  • Safari 3.2+
  • Opera 9.6+

I've personally tested it myself on the following, which it works on:

  • Chrome 36 on Windows 7
  • FF29 on Windows 7
  • FF30 & FF32 on WindowsXP
  • IE9 on Windows 7
  • IE10 on Windows 8
  • IOS7
  • Default browser on Android 4.1.2 on a Sony Xperia Acro S
  • Chrome 36 on Android 4.1.2 on a Sony Xperia Acro S

And of course I double checked that it doesn't work in IE8, and it doesn't.

Examples

As linked to at the start of this post, have a look at the example here or download the compressed version here.

Try it yourself

I given a couple of pretty basic examples but the world is your oyster; try it out where needed and see what you can do. I personally came across :not and :empty when needing to suppress the styling of some empty messages divs in a CMS system - I'd keep seeing blank yellow or blue boxes all over the place. Using :empty I was able to remove the existing styling when the element didn't have a message, without having to hack the core stylesheet.



Related posts:


Comments