I have a file like
<div>
<div class="abc">
<div>
<!--some more divs inside-->
</div>
</div>
</div>
What I want to do is to apply styles only to the first div. I tried to use div:not(.abc, .abc *)
, div:not(.abc):not(.abc *)
, div:not(.abc), div:not(.abc) *
but none of these worked. It would be hard to edit the html, because there would be many files to be edited. Also the code shown above appears in different places, so using >
selector is not the solution... Does someone know how to do this?
You cannot reliably use the :not()
selector in CSS for excluding an element and/or its descendants. The reason for it is explained in this answer (and some others that it links to):
You can't use combinators. This works in jQuery, but not CSS:
/* * Grab everything that is neither #foo itself nor within #foo. * Notice the descendant combinator (the space) between #foo and *. */ :not(#foo, #foo *)
This one is particularly nasty, primarily because it has no proper workaround. There are some loose workarounds (1 and 2), but they usually depend on the HTML structure and are therefore very limited in utility.
And since your markup is unpredictable enough that you cannot edit it or use the >
selector, I'm afraid there's not much of a way out for you other than to either find a way to apply a class to your top div
and use that class, as demonstrated by Fluidbyte, and/or use jQuery, as implied above.
I usually find it's easier to include what you need via a class then try to exclude descendant elements. See the fiddle here: http://jsfiddle.net/cLtHg/
That takes care of inheritance issues and is much more cross-browser friendly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With