我已经试过了;
@mixin text-format{
>p, >ul, >h1, >h2, >h3, >h4, >h5{
&:last-of-type{
background-color:green;
}
}
}
.text-body{
@include text-format;
}
纯 CSS
.text-body > p:last-of-type, .text-body > ul:last-of-type, .text-body > h1:last-of-type, .text-body > h2:last-of-type, .text-body > h3:last-of-type, .text-body > h4:last-of-type, .text-body > h5:last-of-type {
background-color: green;
}
这会选择每个元素类型的最后一个实例,但该元素类型独占。我只是想选择 div 中的最后一个元素,不管它是什么,但在选择器中的指定元素类型中。
fiddle ; http://jsfiddle.net/bazzle/bcLt62jx/
最佳答案
听起来你可能正在寻找
.text-body > :nth-last-child(1 of p, ul, h1, h2, h3, h4, h5)
来自 Selectors 4(最初指定为 :nth-last-match()
)。这将潜在匹配列表限制为仅那些元素类型,并选择它们在父元素 .text-body
中的最后一次出现。一个例子:
<div class="text-body">
<h1></h1>
<p></p>
<ul></ul>
<h2></h2>
<p></p>
<span></span>
</div>
在这个例子中,有六个 child ,其中五个是 p, ul, h1, h2, h3, h4, h5
中的任何一个。这五个元素中的最后一个元素是紧接在 p
之前的 span
,因此它与上面的选择器匹配。 h1
将匹配等效的 :nth-child()
表达式,而 span
永远不会匹配给定选择器列表的任何此类表达式 — 事实上,span
本身可以表示为 :not(p, ul, h1, h2, h3, h4, h5)
。
虽然 :nth-child()
、 :nth-last-child()
和 :not()
都是在 Selectors 3 中引入的,但 selector-list 参数是 Selectors 4 的新参数。但是还没有人实现它,也不知道什么时候会实现。不幸的是,没有使用当前可用的等效项,因为它基本上与 this question 相同,除了不是类选择器,您正在寻找匹配 池的第 n 个(最后一个)子项 选项。在这两种情况下,您都在处理元素子元素的某个子集的第 n 次出现。
最好的办法是使用 JavaScript,例如,在页面加载时向这些元素类型的最后一个实例添加一个类。与 native DOM/选择器 API 类似:
var types = document.querySelectorAll('.text-body > p, .text-body > ul, .text-body > h1, .text-body > h2, .text-body > h3, .text-body > h4, .text-body > h5');
types[types.length - 1].className += ' last';
...与下面的 jQuery 相比,这是相当可憎的:
$('.text-body').children('p, ul, h1, h2, h3, h4, h5').last().addClass('last');
注意
:nth-last-child(1 of p, ul, h1, h2, h3, h4, h5)
不等同于
:last-child:matches(p, ul, h1, h2, h3, h4, h5)
因为后者匹配其父元素的最后一个子元素当且仅当它是这些元素类型中的任何一种时。换句话说,:last-child:matches(...)
是 Selectors 4 等同于 p, ul... { &:last-child { ... } }
(Harry 回答的第二部分)。
关于html - 使用 CSS 定位一组元素类型中的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31676178/