CSS General Sibling Selector特异性

时间:2014-12-11 04:14:21

标签: css css-selectors css-specificity

对于文件:

<h1>Section 1</h1>
<p>I came after a h1 and should be red.</p>
<p>I came after a h1 and should be red.</p>

<h2>Section 2</h2>
<p>I came after a h2 and should be green.</p>
<p>I came after a h2 and should be green.</p>

<h1>Section 3</h1>
<p>I should be the same color as the section one text?</p>
<p>I should be the same color as the section one text?</p>

我试着设计它:

h1 ~ p {
    color: red;
}

h2 ~ p {
    color: green;
} 

http://jsfiddle.net/4ks7j938/7/

我希望第1段和第3段具有相同的样式,第三段与更具体的h1 ~ p选择器匹配,因为h1h2更接近兄弟。但是,在我的测试中,结果是第2段和第3段的样式相同。

两个问题:

css选择器规范是否实际在某处指定了此行为?这里似乎可以解释css spec on the General sibling selector

如何实现第1段和第3段以相同方式设计的预期结果?我无法向html添加类或任何属性,我只能控制css。

5 个答案:

答案 0 :(得分:5)

两个选择器具有相同的特异性,导致h2 ~ p优先的原因是它在之后定义,因此级联h1 ~ p。兄弟姐妹的亲密程度并不重要 对于您想要的行为,您可以使用adjacent sibling selector +

如果您更改h1 ~ p后会发现它需要经得起考验

&#13;
&#13;
h2 ~ p {
    color: green;
}

h1 ~ p {
    color: red;
}
&#13;
<h1>Section 1</h1>
<p>I came after a h1 and should be red.</p>
    
<h2>Section 2</h2>
<p>I came after a h2 and should be green.</p>

<h1>Section 3</h1>
<p>I should be the same color as the section one text?</p>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

Musa似乎是正确的,你只能在一般情况下使用CSS来解决这个问题。

但这是三个部分的一个解决方案:

h1 ~ p,
h1 ~ h1 ~ p {
    color: red;
}

h2 ~ p {
    color: green;
}

http://jsfiddle.net/4ks7j938/12/

或者,根据交错的数量,这可能也有效,并且可能扩展到更多部分:

h1 ~ p,
h1 ~ h2 ~ h1 ~ p,
h1 ~ h2 ~ h1 ~ h2 ~ h1 ~ p
/* add more as needed */ {
    color: red;
}

h2 ~ p,
h2 ~ h1 ~ h2 ~ p,
h2 ~ h1 ~ h2 ~ h1 ~ h2  ~ p
/* add more as needed */ {
    color: green;
}

http://jsfiddle.net/4ks7j938/15/

然而,这两种方法都没有特别的可扩展性。

答案 2 :(得分:1)

这是一个多么棘手的问题! 如果您有权添加一些jQuery,那么可能会使用一些traversing methods。 以下是有效的,但您需要使其符合您的特定需求,因此另一种方法可能会更好。

$( "h1" )
  .nextUntil( "h2" )
    .css( "color", "red" );

$( "h2" )
  .nextUntil("h1")
    .css( "color", "green" );

updated fiddle

答案 3 :(得分:0)

您的代码在第一行中包含h1标记的CSS,因此它会查找所有p标记,该标记是h1标记的兄弟,并将红色应用于所有p标记1}}标签。在下一行,它会找到两个p标记,它们位于第一个&#39; h1 tag and those two p`标记将被应用到第二个css。这是一个令人兴奋的问题。 现在您的问题的解决方案是css3 adjecent siblings selector

看看这个小提琴:http://jsfiddle.net/4ks7j938/9/

答案 4 :(得分:-1)

您可以使用以下代码:

h1 ~ p {
    color: red; 
}
h2+p{
    color: green; 
}
相关问题