CSS Selector to Select Elements Not Having Certain Class / Attribute / Type


Using the CSS :not() pseudo-class, we can refine our styling by selecting those elements which do not have a specific value or does not match a selector.

Select Elements not Having a Child Selector

To select elements not having a child selector, use the :not pseudo-class in CSS.

Here, we have a child selector. The CSS child selector is used to select all the child elements with a particular parent element. It selects all the <p> elements that are children of <div> i.e.

div>p

But we have selected elements not having this div>p −

p:not(div>p) {
   background-color: orange;
   font-size: 1.4em;
   font-style: italic;
   color: blue;
}

Example

The following examples illustrate CSS :not pseudo-class −

<!DOCTYPE html>
<html>
<head>
   <style>
      p {
         background-color: cornflowerblue;
         color: white;
      }
      p:not(div>p) {
         background-color: orange;
         font-size: 1.4em;
         font-style: italic;
         color: blue;
      }
   </style>
</head>
<body>
   <div>
      <p>Curabitur sapien diam, imperdiet ut est sed, blandit blandit velit. Nunc viverra nunc id ligula ultricies, a fringilla lacus interdum. <span>Sed vel diam at magna pellentesque porttitor.</span></p>
      <h3>Demo</h3>
   </div>
   <p>This is a demo text.</p>
</body>
</html>

Select Elements not Having a Certain Class

We will select elements not having a certain class using the :not selector as shown below −

div:not(.parent) {
   box-shadow: inset 0 0 24px tomato;
   padding: 2%;
}

Above, we have the following parent class −

<div class="parent">
   <div class="one">
      <div class="two"></div>
      <div class="two"></div>
   </div>
   <div class="one"></div>
</div>

Example

Let us see an example to select elements not having a certain class −

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         margin: 2%;
         background-color: cadetblue;
         padding: 10%;
         height: 80px;
      }
      div:not(.parent) {
         box-shadow: inset 0 0 24px blue;
         padding: 2%;
      }
      .parent{
         border: 8px ridge orange;
         color: white;
      }
      .one {
         background-color: lightgreen;
         border: 4px groove gray;
      }
      .two{
         height: 20px;
      }
   </style>
</head>
<body>
   <div class="parent">Parent div
      <div class="one">
         <div class="two"></div>
         <div class="two"></div>
      </div>
      <div class="one"></div>
   </div>
</body>
</html>

Updated on: 31-Oct-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements