我可以将first-child和last-child伪元素应用于具有不同子容器中相同类的div吗?在下面的示例中,带有“选中框”类的div都存储在“1st-container”下,但是路上还有2个容器:
<div class="1st-container">
<div class="2nd-container">
<div class="3rd-container">
<div class="box selected"> // this div should have first-child pseudo elements
<div class="box">
</div>
</div>
<div class="2nd-container">
<div class="3rd-container">
<div class="box selected">
<div class="box">
<div class="box">
<div class="box">
</div>
</div>
<div class="2nd-container">
<div class="3rd-container">
<div class="box selected"> // this div should have last-child pseudo
<div class="box">
</div>
</div>
</div>
纯css是否可行?
答案 0 :(得分:2)
你不能做你所描述的,因为在这两种情况下,"box selected"
是其父母的第一个孩子。不过,你可以采取不同的方法。例如,您可以像这样定位这两个div:
.2nd-container:first-child .selected,
.2nd-container:last-child .selected
{}
正如所指出的那样,将2
替换为非数字,因为这不起作用。我被主要问题分心了。 : - )
答案 1 :(得分:1)
首先,您不能使用数字来启动课程或ID。
其次,你只需要对第二个元素的第一个和最后一个孩子进行查找,你应该能够找到你需要的元素。
.box {
height: 20px;
width: 400px;
background: blue;
}
.box.selected {
background: red;
}
.two-container:first-child .box.selected,
.two-container:last-child .box.selected {
background: green;
}
&#13;
<div class="one-container">
<div class="two-container">
<div class="three-container">
<div class="box selected">// this div should have first-child pseudo elements</div>
<div class="box"></div>
</div>
</div>
<div class="two-container">
<div class="three-container">
<div class="box selected"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
<div class="two-container">
<div class="three-container">
<div class="box selected">// this div should have last-child pseudo</div>
<div class="box"></div>
</div>
</div>
</div>
&#13;
答案 2 :(得分:0)
使用JS看起来比CSS更容易:
var selected = document.querySelectorAll('.one-container .box.selected');
selected[0].style.background = selected[selected.length-1].style.background='green';