我想知道为什么我不能选择具有特定类的元素的最后一个子元素。它只适用于所有元素具有相同类但但是一旦最后一个元素没有类,它就不起作用。
我想念的是什么?
.headerWithIcons div {
width: 50px;
height: 50px;
background-color: red;
display: inline-block;
}
.headerIcons:last-child {
opacity: .5;
}
.headerIconsDIV:last-child {
opacity: .5;
}

<div class="headerWithIcons">
<div class="headerIconsDIV">Test</div>
<div class="headerIconsDIV">Test</div>
<div class="headerIconsDIV">Test</div>
<div class="headerIconsDIV">Test</div>
<!-- Only working when this div has the same class like the elements above -->
<div class="">Test</div>
</div>
&#13;
非常感谢!
答案 0 :(得分:1)
遗憾的是,没有这样的选择器可以选择类的最后一个,当它之后有相同类型的其他元素具有不同的类或没有类时。您只能获取最后一个元素类型(:last-of-type
)和最后一个元素(:last-child
)和特定元素计数(:nth-child()
)。但是,您可以使用:nth-last-of-type(2)
向后计数。这将选择倒数第二个元素。
.headerWithIcons div {
width: 50px;
height: 50px;
background-color: red;
display: inline-block;
}
.headerIcons:last-child {
opacity: .5;
}
.headerIconsDIV:nth-last-of-type(2) {
opacity: .5;
}
&#13;
<div class="headerWithIcons">
<div class="headerIconsDIV">Test</div>
<div class="headerIconsDIV">Test</div>
<div class="headerIconsDIV">Test</div>
<div class="headerIconsDIV">Test</div>
<!-- Only working when this div has the same class like the elements above -->
<div class="">Test</div>
</div>
&#13;
答案 1 :(得分:0)
不确定你想要做什么,但是如果你想将不同的东西与你div的最后一个孩子div关联起来,那么这就是&#39;:
.headerWithIcons div:last-child {
/** your styles for your last div */
}
答案 2 :(得分:-1)
Lastchild适用于子元素,而不是父元素 - 因此,子元素必须是完全相同的类型(不一定是同一类)。
要根据classname获取最后一个孩子,您可以使用:
.headerIcons:last-child
要抓住没有类名的最后一个孩子,你可以使用:
.headerWithIcons div:last-child
答案 3 :(得分:-1)
只需在类名和冒号之间留一个空格。它会工作。我编辑了你的代码,它按照你想要的方式工作
.headerWithIcons div {
width: 50px;
height: 50px;
background-color: blue;
display: inline-block;
}
.headerWithIcons :last-child{
opacity: .1;
}
<div class="headerWithIcons">
<div class="headerIconsDIV">Test</div>
<div class="headerIconsDIV">Test</div>
<div class="headerIconsDIV">Test</div>
<div class="headerIconsDIV">Test</div>
<!-- Only working when this div has the same class like the elements above -->
<div class="LastElement">Test</div>
</div>