在 CSS 中,我们可以使用 ":nth-last-child" 选择器选中最后一个子元素的前一个元素,即倒数第二个子元素。
/* 选中倒数第二个子元素 */
element:nth-last-child(2) {
/* 样式属性 */
} 该选择器的用法与 ":nth-child" 选择器类似,只是将下标倒序计算。例如,在以下 HTML 结构中:
<div>
<p>第一个子元素</p>
<p>第二个子元素</p>
<p>第三个子元素</p>
<p>倒数第二个子元素</p>
<p>最后一个子元素</p>
</div> 我们可以使用 ":nth-last-child" 选择器选中第四个 <p> 元素:
div p:nth-last-child(2) {
/* 样式属性 */
} 需要注意的是,该选择器并不支持低版本的 Internet Explorer 浏览器。
除了 ":nth-last-child" 选择器,我们还可以使用 ":nth-last-of-type" 选择器在同一类型的元素中选中倒数第二个。例如,在以下 HTML 结构中:
<div>
<p>第一个元素</p>
<a>第二个元素</a>
<p>第三个元素</p>
<a>倒数第二个元素</a>
<p>最后一个元素</p>
</div> 我们可以使用 ":nth-last-of-type" 选择器选中第四个 <a> 元素:
div a:nth-last-of-type(2) {
/* 样式属性 */
}