[html] Can I write a CSS selector selecting elements NOT having a certain class or attribute?

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

This question is related to html css css-selectors

The answer is


:not([class])

Actually, this will select anything that does not have a css class (class="css-selector") applied to it.

I made a jsfiddle demo

_x000D_
_x000D_
    h2 {color:#fff}_x000D_
    :not([class]) {color:red;background-color:blue}_x000D_
    .fake-class {color:green}
_x000D_
    <h2 class="fake-class">fake-class will be green</h2>_x000D_
    <h2 class="">empty class SHOULD be white</h2>_x000D_
    <h2>no class should be red</h2>_x000D_
    <h2 class="fake-clas2s">fake-class2 SHOULD be white</h2>_x000D_
    <h2 class="">empty class2 SHOULD be white</h2>_x000D_
    <h2>no class2 SHOULD be red</h2>
_x000D_
_x000D_
_x000D_

Is this supported? Yes : Caniuse.com (accessed 02 Jan 2020):

  • Support: 98.74%
  • Partial support: 0.1%
  • Total:98.84%

Funny edit, I was Googling for the opposite of :not. CSS negation?

selector[class]  /* the oposite of :not[]*/

If you want a specific class menu to have a specific CSS if missing class logged-in:

body:not(.logged-in) .menu  {
    display: none
}

Using the :not() pseudo class:

For selecting everything but a certain element (or elements). We can use the :not() CSS pseudo class. The :not() pseudo class requires a CSS selector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.

Examples:

_x000D_
_x000D_
/* This query selects All div elements except for   */_x000D_
div:not(.foo) {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Selects all hovered nav elements inside section element except_x000D_
   for the nav elements which have the ID foo*/_x000D_
section nav:hover:not(#foo) {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* selects all li elements inside an ul which are not odd */_x000D_
ul li:not(:nth-child(odd)) { _x000D_
  color: red;_x000D_
}
_x000D_
<div>test</div>_x000D_
<div class="foo">test</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<section>_x000D_
  <nav id="foo">test</nav>_x000D_
  <nav>Hover me!!!</nav>_x000D_
</section>_x000D_
<nav></nav>_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
  <li>1</li>_x000D_
  <li>2</li>_x000D_
  <li>3</li>_x000D_
  <li>4</li>_x000D_
  <li>5</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:

_x000D_
_x000D_
/* This selector has a higher specificity than the #foo below */_x000D_
#foo:not(#bar) {_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
/* This selector is lower in the cascade but is overruled by the style above */_x000D_
#foo {_x000D_
  color: green;_x000D_
}
_x000D_
<div id="foo">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor_x000D_
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>
_x000D_
_x000D_
_x000D_


Just like to contribute that the above answers of :not() can be very effective in angular forms, rather than creating effects or adjusting the view/DOM,

input.ng-invalid:not(.ng-pristine) { ... your css here i.e. border-color: red; ...}

Ensures that on loading your page, the input fields will only show the invalid (red borders or backgrounds, etc) if they have data added (i.e. no longer pristine) but are invalid.


As others said, you simply put :not(.class). For CSS selectors, I recommend visiting this link, it's been very helpful throughout my journey: https://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048

div:not(.success) {
  color: red;
}

The negation pseudo class is particularly helpful. Let's say I want to select all divs, except for the one which has an id of container. The snippet above will handle that task perfectly.

Or, if I wanted to select every single element (not advised) except for paragraph tags, we could do:

*:not(p) {
  color: green;
}

You can use :not(.class) selector as mentioned before.

If you care about Internet explorer compatibility I recommend you to use http://selectivizr.com/.

But remember to run it under apache otherwise you won't see the effect.


I think this should work:

:not(.printable)

From "negative css selector" answer.


The :not negation pseudo class

The negation CSS pseudo-class, :not(X), is a functional notation taking a simple selector X as an argument. It matches an element that is not represented by the argument. X must not contain another negation selector.

You can use :not to exclude any subset of matched elements, ordered as you would normal CSS selectors.


Simple example: excluding by class

div:not(.class)

Would select all div elements without the class .class

_x000D_
_x000D_
div:not(.class) {_x000D_
  color: red;_x000D_
}
_x000D_
<div>Make me red!</div>_x000D_
<div class="class">...but not me...</div>
_x000D_
_x000D_
_x000D_


Complex example: excluding by type / hierarchy

:not(div) > div

Would select all div elements which arent children of another div

_x000D_
_x000D_
div {_x000D_
  color: black_x000D_
}_x000D_
:not(div) > div {_x000D_
  color: red;_x000D_
}
_x000D_
<div>Make me red!</div>_x000D_
<div>_x000D_
  <div>...but not me...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Complex example: chaining pseudo selectors

With the notable exception of not being able to chain/nest :not selectors and pseudo elements, you can use in conjunction with other pseudo selectors.

_x000D_
_x000D_
div {_x000D_
  color: black_x000D_
}_x000D_
:not(:nth-child(2)){_x000D_
  color: red;_x000D_
}
_x000D_
<div>_x000D_
  <div>Make me red!</div>_x000D_
  <div>...but not me...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Browser Support, etc.

:not is a CSS3 level selector, the main exception in terms of support is that it is IE9+

The spec also makes an interesting point:

the :not() pseudo allows useless selectors to be written. For instance :not(*|*), which represents no element at all, or foo:not(bar), which is equivalent to foo but with a higher specificity.


Example

  [class*='section-']:not(.section-name) {
    @include opacity(0.6);
    // Write your css code here
  }

// Opacity 0.6 all "section-" but not "section-name"


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to css-selectors

Angular 2: How to style host element of the component? How to click a href link using Selenium How do I apply a style to all children of an element How to write a CSS hack for IE 11? :last-child not working as expected? Need to find element in selenium by css jQuery select child element by class with unknown path How do I select an element that has a certain class? What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing? What is the mouse down selector in CSS?