CSS Question

:not selector won't exclude targeted elements

I'm playing around with the :not selector, and would like to produce an image icon for every single area in my HTML file except for the navigation section. Each time I try the CSS below, it still produces the .PDF image logo in the nav section as well as everywhere else.



body *:not(nav) [href*="pdf"]:after {
content: url("pdf.png");
padding-left: 10px;
}

<nav style="top: 400px; position: relative;">
<ul class="nav-ul">
<li class="nav-li-2 nav-mobile-li"><a class="nav-li-a" href="">Hello</a></li>
<li class="nav-li-2 nav-mobile-li"><a class="nav-li-a" href="">Hello2</a></li>
<li class="nav-li-2 nav-mobile-li"><a class="nav-li-a" href="pdf.png">Another PDF</a></li>
<a href="pdf.png">PDF</a>
<a href="intmark.png">INTMARK</a>
<a href="browser.png">BROWSER</a>
</ul>
</nav>
<p>
<a href="pdf.png">PDF</a> This is just a paragraph in a page with fixed footer</p>
<p>This is just a paragraph in a page with fixed footer</p>




Answer

You're trying to select elements with href attributes that are descendants of any element except nav.

The problem with your selector is that the href attributes inside the nav element are also descendants of ul and li elements, so :not() doesn't match.

Remove the ul and li tags from your code, and your selector works as intended.

Here's a possible solution:

body > *:not(nav) > * {
  background-color: red;
}
<nav>
  <ul class="nav-ul">
    <li class="nav-li-2"><a class="nav-li-a" href="">Hello</a></li>
    <li class="nav-li-2"><a class="nav-li-a" href="">Hello2</a></li>
    <li class="nav-li-2"><a class="nav-li-a" href="pdf.png">Another PDF</a></li>
    <a href="pdf.png">PDF</a>
    <a href="intmark.png">INTMARK</a>
    <a href="browser.png">BROWSER</a>
  </ul>
</nav>

<p>
  <a href="pdf.png">PDF</a> This is just a paragraph in a page with fixed footer
</p>

OR, more specifically to your question:

body > *:not(nav) > [href*="pdf"]::after {
  content: "";
  background-color: red;
  display: inline-block;
  width: 10px;
  height: 10px;
}
<nav>
  <ul class="nav-ul">
    <li class="nav-li-2"><a class="nav-li-a" href="">Hello</a></li>
    <li class="nav-li-2"><a class="nav-li-a" href="">Hello2</a></li>
    <li class="nav-li-2"><a class="nav-li-a" href="pdf.png">Another PDF</a></li>
    <a href="pdf.png">PDF</a>
    <a href="intmark.png">INTMARK</a>
    <a href="browser.png">BROWSER</a>
  </ul>
</nav>

<p>
  <a href="pdf.png">PDF</a> This is just a paragraph in a page with fixed footer
</p>

Comments