Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

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 interesting 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 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).

1 Answer

0 votes
by (40.7k points)

You can try adding a class selector to the :not() pseudo-class like this:

:not(.printable) {

    /* Styles */

}

Note: If you want better browser support (IE8 and older don't support :not()), then you're probably better off creating style rules for elements that do have the "printable" class. Even if that isn't feasible despite what you say about your actual markup, you will have to work your markup around that limitation. The important thing to remember is- 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, even if the display is not inherited, setting display: none on a :not(.printable) will prevent it and all of its descendants from displaying because it removes the element and its subtree from layout completely. You can try using visibility: hidden instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did.

Related questions

Browse Categories

...