如何在混合容器中选择类的第一个孩子/最后一个孩子? [英] How can select first child/last child of class in a mixed container?
问题描述
我可以在具有各种类别子项的div中选择类别的第一个和最后一个子项吗?
Can I select the first and last children of a class in a div that has children of with various classes?
例如:
<div class="main">
<div class="red"></div>
<div class="red"></div>
<div class="red"></div>
<div class="black"></div>
<div class="black"></div>
<div class="black"></div>
<div class="green"></div>
<div class="green"></div>
<div class="green"></div>
</div>
我想选择的首子和最后子
。这是可能吗?
I want to select first-child and last-child of .black
. Is that possible?
推荐答案
使用 nth-child
或 nth-of-type
。
.main .black:nth-child(2n) {
color: yellow;
}
或如果您希望它们是分开的
Or if you want them to be separate
.main .black:nth-child(5n - 6) {
color: yellow;
}
.main .black:nth-child(5n - 4) {
color:purple;
}
函数计算使用 n = / code>:
:nth-child(2n)
$ c>选择所有奇数元素,:nth-child(2n-1)
选择所有偶数元素,依此类推。
The function calculates using n = element of type
, so :nth-child(n)
would select every element, :nth-child(2n)
selects all odd elements, :nth-child(2n-1)
selects all even elements, and so on. You simply have to come up with a function that gets you the elements you want
另一个选项可能是添加另一个类到类的第一个和/或最后一个元素
Another option may be to add another class to the first and/or last element of class
您可以通过组合两个选择器(例如Jonathan)来选择具有动态数量的元素的第一个子元素(我更喜欢 div:not(。黑色)+ div.black
个人)。然而,选择具有动态数量元素的类的最后一个元素的唯一方法是使用Javascript或类似jQuery的库,如下所示:
You can select the first child with a dynamic number of elements with the class by combining two selectors like Jonathan said (I prefer div:not(.black) + div.black
personally). However, the only way to select the last element with a class with a dynamic number of elements given there is no previous sibling selector is to use Javascript or a library like jQuery as follows:
Javascript
Javascript
var blackElems = document.getElementsByClassName('black');
blackElems[blackElems.length - 1].style.color = 'purple';
jQuery
$('.main .black:last').css({ 'color' : 'purple' });
这篇关于如何在混合容器中选择类的第一个孩子/最后一个孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!