:last-child 是相对于父级的,所以这里:
<div class="cont">
<span class="help">
<div class="wrapper">aaaa</div>
</span>
<span class="help">
<div class="wrapper">bbbbb</div>
</span>
</div>
带有文字aaaa的.wrapper是带有.help类的第一个<span>的:last-child,带有文字bbbbb的第二个.wrapper也是第二个的:last-child <span> 类 .help。
您需要将:last-child 选择器应用到.help,这将选择最后一个.help,然后使用descendant 或child 选择器来定位其中的.wrapper:
.help:last-child > .wrapper
如果您还可以在单个.help 中包含多个.wrapper,并且您只想选择最后一个,那么它将是:
.help:last-child > .wrapper:last-child
这是一个例子:
body {
font-family: monospace;
font-size: 16px;
}
.cont {
border: 3px solid #000;
margin: 0 0 3px;
}
.help + .help {
margin: 3px 0 0;
}
.wrapper {
background: #F0F;
padding: 1px 6px;
}
.help:last-child > .wrapper:last-child {
background: #FF0;
}
<div class="cont">
<div class="help">
<div class="wrapper">AAA</div>
</div>
<div class="help">
<div class="wrapper">BBB</div>
</div>
</div>
<div class="cont">
<div class="help">
<div class="wrapper">CCC</div>
</div>
<div class="help">
<div class="wrapper">DDD</div>
</div>
<div class="help">
<div class="wrapper">EEE 1</div>
<div class="wrapper">EEE 2</div>
<div class="wrapper">EEE 3</div>
</div>
</div>
正如您在 cmets 中指出的那样,如果 .cont 中的最后一个元素不是 .help,但前一个元素是,则不会选择这个(前一个)。
最好的选择是使用:nth-last-child( <nth> [ of <selector># ]? ):
.help:nth-last-child(1 of .help) > .wrapper:last-child
但对Selectors Level 4 的支持率仍然很低……
具有良好支持的替代方法是使用:last-of-type,但它有一个限制:现在,用于.help 的元素必须不同于用作@ 的子元素(直接后代)的其他元素987654355@:
body {
font-family: monospace;
font-size: 16px;
}
.cont {
border: 3px solid #000;
margin: 0 0 3px;
}
.help + .help {
margin: 3px 0 0;
}
.foo {
display: block;
background: #0FF;
margin: 3px 0 0;
padding: 1px 6px;
}
.wrapper {
background: #F0F;
padding: 1px 6px;
}
.help:last-of-type > .wrapper:last-child {
background: #FF0;
}
<div class="cont">
<div class="help">
<div class="wrapper">CCC</div>
</div>
<div class="help">
<div class="wrapper">DDD</div>
</div>
<div class="help">
<div class="wrapper">EEE 1</div>
<div class="wrapper">EEE 2</div>
<div class="wrapper">EEE 3</div>
</div>
<!-- Note I'm using a <span> here -->
<span class="foo">Hi there.</div>
</div>