I would like to write a CSS selector rule that selects all elements that don't have a certain class. For example, given the following HTML:
<html class="printable">
<body class="printable">
<h1 class="printable">Example</h1>
<nav>
<!-- Some menu links... -->
</nav>
<a href="javascript:void(0)" onclick="javascript:self.print()">Print me!</a>
<p class="printable">
This page is super interresting and you should print it!
</p>
</body>
</html>
I would like to write a selector that selects all elements that don't have the "printable" class which, in this case, are the nav and a elements.
Is this possible?
NOTE: in the actual HTML where I would like to use this, there are going to be a lot more elements that don't have the "printable" class than do (I realize it's the other way around in the above example).
Typically you add a class selector to the :not()
pseudo-class like so:
:not(.printable) {
/* Styles */
}
:not([attribute]) {
/* Styles */
}
But if you need better browser support (IE8 and older don't support :not()
), you're probably better off creating style rules for elements that do have the "printable" class. If even that isn't feasible despite what you say about your actual markup, you may have to work your markup around that limitation.
Keep in mind that, depending on the properties you're setting in this rule, some of them may either be inherited by descendants that are .printable
, or otherwise affect them one way or another. For example, although display
is not inherited, setting display: none
on a :not(.printable)
will prevent it and all of its descendants from displaying, since it removes the element and its subtree from layout completely. You can often get around this by using visibility: hidden
instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.