Search code examples
htmlcsscss-selectorspseudo-class

Use CSS :not() to target selected content in an element


I have a .header div with a span maindomain and a div otherdomains inside of it:

<div class="header"><span class="maindomain">LatestFooty.co.uk</span> is currently available for sale, along with:
<div class="otherdomains">    
LatestFootie.com<br>
LatestFootie.co.uk
</div>
</div>

I'm trying to target the is currently available for sale, along with:, without touching the contents of .maindomain or .otherdomains. I understand that the best approach to this might be to wrap it in a span and target that instead, but at this point I'd like to figure out why I can't get the :not pseudo-class working.

Here is what I have:

@media (min-width:300px) and (max-width:450px) {
  .header:not(.maindomain):not(.otherdomains) {
  font-style: italic;  
  }
}

As far as I can tell, the syntax is correct, and I don't think it's a specificity issue because !important doesn't make a difference. What am I doing wrong?


Solution

  • .header:not(.maindomain):not(.otherdomains) only targets elements which have the .header class and don't have the .maindomain and/or the .otherdomain class themselves.

    Your rules currently say:

    <div class="header"> is targeted

    <div class="header maindomain"> is not targeted

    <div class="header otherdomains"> is not targeted

    <div class="header maindomain otherdomains"> is not targeted

    But this is not what you want to do here obviously.

    You cannot apply rules to the .header class depending on classes of its children with CSS alone.

    There's an approved answer to your question here which might guide you in the right direction (using JavaScript or jQuery in that case).