I had completely forgotten about the :not
selector until today, when a colleague asked me if there was away to apply a style to a class but exclude one of the child elements with CSS.
Typically this wouldn’t be the ideal solution to the problem but we were unable to change the HTML we were working with. The markup in question was along the following lines:
<div class="example-div">
<span>Label text</span>
Data text
</div>
What my colleague wanted was for the span
to be set in the default sans-serif font, already defined, whilst the rest of the text set in a mono-spaced font.
One way we could have solved it would be to apply the style to the entire div
and then reset the span
to the default font, like this:
.my-div {
font-family: "Courier New", Courier, monospace;
}
.my-div span {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
The problem with this is that we are changing a style which has already been defined, just to change it back to its initial value. Enter the :not
selector:
.my-div:not(span) {
font-family: "Courier New", Courier, monospace;
}
That’s much better. Browser support for this particular selector is actually pretty good too. All modern browsers (Chrome, Firefox, Opera and Safari) and IE9 upwards support it.
I admit this isn’t revolutionary but it was the first time I'd had a reason to use this selector and in the spirit of Chris Coyier’s recent entry on the Pastry Box Project, I decided to write about a problem that I solved today. After all, there is a chance that it may be of use to someone somewhere.