开发者

Is it possible to set css rules based on value of non-sibling elements?

Say you have this code:

<div class="hello">
    <div class="cat dog"/>
</div>
<div class="notASibling" />

is 开发者_Python百科it possible to set a property of notASibling, based on the class value of an element that is not a sibling? For example, in the above code I may want to set the display property of notASibling to hidden if the hello > cat class is not a dog.

If notASibling was a sibling of "cat dog", I could simply say:

.cat:not(.dog) ~ .notASibling{ display:none; }


This isn't possible in CSS. Your only real option here would be to use Javascript. The jQuery library is based around the idea of using enhanced CSS selectors for selecting elements to manipulate them, and you could do that here:

prevWasADog = $(".notASibling").prev().children('.cat').eq(0).is('.dog');


The answer is no. Spontaneously, you might think about combining the child combinator and sibling combinator, i.e. like this:

.notASibling ~ .hello > .cat:not(.dog) { display: none }

But this is not possible since in the CSS 3 selectors definition (http://www.w3.org/TR/css3-selectors/) selectors may only use combinators with "simple selector sequences" as their operands, not other selectors. So if you follow the W3C's grammar rules you can only use one combinator within a selector.


You can't reach a non-sibling in pure CSS. You can do this in JavaScript. If you want a pure CSS solution, consider refactoring your DOM a bit. Maybe something like this:

<div class='dog'>
    <div class='hello'>
        <div />
    </div>
    <div class='notASibling' />
</div>


.cat div.notASibling {
    /* special styles for cats */
}
.dog div.notASibling {
    /* special styles for dogs */
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜