假设这个HTML:
<h1>heading</h1>
<p>foo</p>
<p>bar</p><!---this should be selected--->
<h1>heading</h1>
<p>foo</p>
<p>bar</p>
<p>foo</p>
<p>bar</p><!---this should be selected--->
并且只能用CSS选择它?
我是这样尝试的:
h1 ~ p:last-child /*wouldn't work*/ /* it would select last-child of p*/
答案 0 :(得分:1)
这对CSS来说根本不可能,因为没有办法向后或向上选择元素(期待CSS4 ......)。您将不得不使用以下其中一个:
<section>
<h1>heading</h1>
<p>foo</p>
<p>bar</p><!---this should be selected--->
</section>
(section p:last-child
)或:
<h1>heading</h1>
<p>foo</p>
<p class="last">bar</p><!---this should be selected--->
(p.last
)或JS:
var e = document.getElementsByTagName('h1');
for (var i = 0; i < e.length; i++) {
var f = e[i].nextSibling;
while (f && f.tagName == 'P') {
var n = f.nextSibling();
if (!n) {
f.classList.add('last');
} else {
f = n;
}
}
}
答案 1 :(得分:0)
<div class="span8">
<h1>heading</h1>
<p>foo</p>
<p>bar</p>
<p>foo</p>
<p>bar</p>
</div>
.span8 > p:last-child{ color:red }
答案 2 :(得分:0)
答案 3 :(得分:-1)