Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid a specific ID inside element in CSS?

Tags:

html

css

I have this structure in html

<div id="A">
   ....
   <div id="B">
      ....
   </div>
   ....
</div>

How can I write a CSS rule, that says, make all a tags color white inside #A, but ignore what's in #B?

I would prefer to have something like :not(#B) and not put another wrapper tag or anything too hardcoded.

Thanks

like image 601
omega Avatar asked Mar 09 '26 05:03

omega


2 Answers

Best solution (although still not perfext):

(Corrected after the comment and with the code of @Amit)

/* Either directly under #A, or in an element in #A that's not #B */
/* The element that's not #B must be a direct child of #A, otherwise */
/* children of children of #B will be selected anyway, as @Amit pointed out. */
#A > a, #A > :not(#B) a { color:red }
<div id="A">
   <a>red</a>
   <div id="B">
      <a>black</a>
      <p>
        <a>black</a>
      </p>
   </div>
   <p>
     <a>red</a>
   </p>
</div>

This still has problems (IE 9+ and not working if #B is wrapped), but it is the best solution we've got.

Incorrect, failing solution (just to show what's wrong):

#A > a, #A :not(#B) a { color:red }
<div id="A">
   <a>red</a>
   <div id="B">
      <a>black</a>
      <p>
        <a>black</a>
      </p>
   </div>
   <p>
     <a>red</a>
   </p>
</div>
like image 72
LarsW Avatar answered Mar 11 '26 18:03

LarsW


Why not do simply:

#A a {
 color:#fff;
}
#B a {
 color:green;
}
like image 33
stckvrw Avatar answered Mar 11 '26 20:03

stckvrw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!