开发者

How to get all child elements excluding grandchildren

See here: http://jsfiddle.net/QVhAZ/4/

How can I use * but only have it apply to direct children? In the example, I'd want it to only apply to the "Child" divs, not the "Grandchild (should not be red)" divs.

I don't want to appl开发者_如何学JAVAy a class to each "child" div, what I want is to say:

div#Root *:depth(1)
{
    color: red;
}


You mean this?

div {margin:20px;}

div#Root > div {color:red;}

div#Root > div > div {color:black;}

http://jsfiddle.net/QVhAZ/20/

Also using * selector selects not only divs but all elements - and it is also much slower since it has to parse all. Note that color will still be inherited by all children so you have to specify the color you want to use for all the rest.


If you want direct children then use the child selector:

div > * {
  /* styles for all direct children of div */
}

Note: color property cascades automatically, so this becomes a bit trickier. You would have to reset the property for the grandchildren (see easwee's answer). But to prove this indeed is the way to go, see border behaving correctly - http://jsfiddle.net/QVhAZ/22/


Try this

div#Root > *
{
    color: red;
}


Maybe you should check out the CSS Selectors reference.

element1 > direct-child {
}


If you want it to work in all browsers (most notably IE6) you should give the grand children divs ids, so you can turn off any styles given in the child for example:

HTML

<div>
  <div class="child">
    <div class="grandchild"></div>
    <div class="grandchild"></div>
    <div class="grandchild"></div>
  </div>
  <div class="child">
    <div class="grandchild"></div>
    <div class="grandchild"></div>
    <div class="grandchild"></div>
  </div>
</div>

STYLE

.child{margin-left:10px;}
.grandchild{margin-left:0px;}

Bit anoying, but it does ensure it works in browsers that dont support css selectors such as div > *

Here is the same example that @easwee used, only tweeked so it works in IE6 http://jsfiddle.net/ajthomascouk/QVhAZ/24/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜