【发布时间】:2015-02-09 11:44:35
【问题描述】:
对于文档:
<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 选择器,因为 h1 比 h2 更接近同级。但是,在我的测试中,结果是第 2 段和第 3 段的样式相同。
两个问题:
css 选择器规范是否真的在某处指定了这种行为? css spec on the General sibling selector 似乎可以在这里解释。
如何实现第 1 段和第 3 段的样式相同的预期结果?我不能向 html 添加类或任何属性,我只能控制 css。
【问题讨论】:
-
calculating selector specificity 上的部分从未提及组合器,因此可以安全地假设甚至推断组合器对选择器的特异性没有影响。
-
至于实现预期结果,Musa 是对的:鉴于您的文档结构,纯 CSS 无法做到这一点。类似问题:stackoverflow.com/questions/10427998/…stackoverflow.com/questions/13330757/…
标签: css css-selectors css-specificity