正如我在my answer here 中解释的那样,:last-child 选择器不能这样工作。此选择器仅指向一个元素,并且始终是其父元素的最后一个子元素。选择的子项不会根据附加到选择器的其他条件而更改。唯一受附加条件影响的是最后一个子元素本身是否被选中。
下面的选择器只是意味着只有当它没有类x时才选择最后一个子li元素而不是选择最后一个没有类的li子元素有类 x.
li li:not(.x):last-child {
color: red;
}
即使在选择器级别 4 中也没有计划引入 先前的兄弟选择器,我认为它们永远不会被引入,因为这与 级联 的含义背道而驰样式表。
然而,第 4 级中指定的选择器可以解决这样的情况,它是 :nth-last-match 伪选择器。对于您的情况,它最终可能类似于以下内容:
li li:nth-last-match(1 of :not(.x))
我假设nth-last-match 将允许否定选择器,因为没有提及它是无效的even though :matches(:not(...)) is said to be invalid。它有可能被标记为无效,在这种情况下我们仍然会发现很难选择这些元素。
根据latest Editor's Draft of the spec,似乎:nth-last-match 选择器不再在范围内(并且已包含在:nth-last-child 选择器中)。因此,选择器将改为:
li li:nth-last-child(1 of :not(.x))
它还谈到了另一种可能对这种情况有用的方法。它是:has 伪选择器。
li li {
color: red; /* apply the styling which needs to be set to the last child without class x */
}
li li:has( ~ li:not(.x)) { /* this selects all li which have a sibling whose class is not x */
color: black; /* override the style for these alone and set them to the default */
}
注意:这只是草稿,可以更改。
一种可能的解决方案是使用 jQuery(或 JavaScript)找出满足条件的最后一个元素,然后为其设置所需的样式或类。
$(document).ready(function() {
$('li ol').map(function() {
return $(this).children().not('.x').get(-1);
}).css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol>
<li>
<ol>
<li>A</li>
<li>B</li>
<li class="x">X</li>
</ol>
</li>
<li>
<ol>
<li>A</li>
<li>C</li>
<li class="x">X</li>
</ol>
</li>
<li>
<ol>
<li>A</li>
<li>D</li>
<li class="x">X</li>
</ol>
</li>
<li>
<ol>
<li>A</li>
<li>D</li>
<li class="ex">X</li>
</ol>
</li>
</ol>