Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude a class with all children in style definition

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?

like image 744
burtek Avatar asked Jun 03 '12 13:06

burtek


2 Answers

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.

like image 57
BoltClock Avatar answered Sep 21 '22 18:09

BoltClock


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.

like image 20
Fluidbyte Avatar answered Sep 19 '22 18:09

Fluidbyte