Times are changing. CSS is becoming a kind of Swiss Army knife for the web. We can already use a range of helpful selectors such as :nth-child, :nth-of-type and :not() to target specific DOM elements. With CSS level 4 selectors, there will be an extra layer of power.
Firstly, there's the :matches pseudo-class. We can use it to match an element against a list of selectors. For example, if we want to apply the same link colour to the different states of an anchor, we can simply do:
a:matches(:hover, :focus, :active){color: #666}
This is a cleaner way of writing the same rule without :matches. One thing to bear in mind is that only compound selectors are allowed as arguments, and you cannot use combinator selectors such as the sibling or descendant selectors. The good news is you can actually try out this out now – Mozilla has implemented -moz-any- which is the equivalent of :matches, and it's been around since Firefox 4.
New pseudoclasses
Next there is the newly introduced time-dimensional pseudoclasses which includes :current, :past and :future. They are used for targeting timedimensional elements such as during speech rendering of a HTML document. For example, we can use :current to render text that is currently being rendered in HTML5 video subtitles:
:current(p) {color: blue}
If we want to target previously rendered element, we can use :past. And similarly, to target upcoming elements, :future will be the one to use.
More power for developers
The ability to style form elements has become more powerful as well with the addition of the pseudoclass :indeterminate. With checkboxes and radio buttons, there are three states: checked, unchecked and indeterminate. We can quite easily style their checked and unchecked states using :checked and :not(:checked).
With CSS level 4, we can style the indeterminate state as well -
:input[type="checkbox"]:indeterminate {background: grey}
The pseudoclass can also be used to style the indeterminate state of <progress> element when no value attribute is included.
At the time of writing, these selectors haven't yet been implemented by any browsers and the specification is constantly changing – but fear not, you can use polyfills such as Sel to get a sneak peek of what these selectors are about. So start experimenting!
Words by: Fiona Chan
Fiona Chan is a senior frontend developer at Learnosity. She loves talking to others about CSS, which has led her to co-found the meet-up group SydCSS (opens in new tab). This article originally appeared in net magazine (opens in new tab)issue 257.