csssass

The :not() CSS pseudo-class not working as expected


A simple one, why

:not(.theme) small{
  font-size: 40px;
}

:not(.theme *) small{
  text-decoration: underline;
}

*:not(.theme *) small{
  font-weight: bold;
}

is taking effect on all small html element? My assumption is that only small elements which are not descendants of a parent with the class theme get affected.

Same goes to

:not(.theme *) .small-class{
  text-transform: capitalize;
}

is affecting all element with small-class.

body {
  background: #6e28d9;
  padding: 0 24px;
  color: white; /* Change my color to yellow */
  margin: 0;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap:20px;
}

.theme small {
  color: black;
}

:not(.theme) small{
  font-size: 40px;
}

:not(.theme *) small{
  text-decoration: underline;
}

*:not(.theme *) small{
  font-weight: bold;
}

small:not(.theme *){
  letter-spacing: 10px;
}

:not(.theme *) .small-class{
  text-transform: capitalize;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="src/style.css">
  </head>
  <body>

    <small>pure small</small>

   <div class="theme">
       <small>small with theme parent</small>
   </div>

    <div class="theme">
       <small class="small-class">small-class with theme parent</small>
   </div>

   <div>
       <small class="small-class">small-class with theme parent</small>
   </div>

  </body>
</html>

Indeed, someone may have better idea on how to apply styling on small element which is not a decendant of any parent with class theme

Here is a little snippet of the rendered result Rendered result


Solution

  • My assumption is that only small elements which are not descendants of a parent with the class theme get affected.

    If that’s what you want, do

    small:not(.theme *) {
      /* … */
    }
    

    i.e. <small> elements that are not descendants of a .theme.

    :not(.theme *) small matches all small elements that are descendants of any element that matches :not(.theme *), which is all of them, since the root <html> element is necessarily :not(.theme *).