Hiding CSS rules with the negation pseudo-class

CSS3 introduces a wide range of new selectors. Effects such as striped table rows and star rating widgets, which previously required additional HTML or even the use of JavaScript, can now be implemented with pure CSS and minimal HTML. However, care must be taken to ensure older browsers correctly display content that uses these selectors. This page shows how to use the negation pseudo-class to hide style rules from browsers with incomplete support for CSS3 selectors.

Motivation

When viewing the form below in a modern web browser, the text field corresponding to the Other option is shown only when that option is selected.

This example uses the following HTML for the final field:

1
2
3
4
5
6
7
8
<div class="otherOption">
  <input id="optionOther" type="radio" name="option" value="other">
  <label for="optionOther">Other</label>
  <div>
    <label for="other">Please specify:</label>
    <input id="other" name="other" type="text">
  </div>
</div>

We can use the CSS3 :checked pseudo-class to hide the div element containing the text field unless the radio button is selected:

1
2
3
4
5
6
7
.otherOption div{
  display : none;
}

.otherOption input:checked + label + div{
  display : block;
}

However, this technique causes problems for browsers that do not recognise the :checked pseudo-class. These browsers will apply the first rule but ignore the second, and hence will never display the text field.

The solution

A rarely-used selector introduced in CSS3 in the negation pseudo-class. This pseudo-class matches those elements not matched by its argument. For example, :not(div) matches elements that are not div elements.

We can incorporate the negation pseudo-class into our earlier code:

1
2
3
4
5
6
7
.otherOption:not(old) div{
  display : none;
}

.otherOption:not(old) input:checked + label + div{
  display : block;
}

Because there is no HTML element called old, the selector :not(old) matches all elements, and therefore leaves the meaning of the rules unchanged. However, because all browsers that support the negation pseudo-class also support the :checked pseudo-class, browsers will either apply both rules or ignore both rules.

Where now?

Found this useful? Share it:

Also in HTML and CSS: