Can I select the first and last children of a class in a div that has children of with various classes?
For example:
<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?
Use nth-child
or nth-of-type
in combination with the class selector.
Live Example
.main .black:nth-child(2n) {
color: yellow;
}
Or if you want them to be separate
This demo
.main .black:nth-child(5n - 6) {
color: yellow;
}
.main .black:nth-child(5n - 4) {
color:purple;
}
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
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
var blackElems = document.getElementsByClassName('black');
blackElems[blackElems.length - 1].style.color = 'purple';
jQuery
$('.main .black:last').css({ 'color' : 'purple' });
No, unfortunately not.
However, it is possible to select the first child of a certain class, by combining two selectors (example):
div.black:first-child,
div:not(.black) + div.black
The first selector selects a black div that's apparently the first child of it's parent. The second selector selects a black div that's preceded by a non-black div. Using these two rules, you can select the first black div.
For more information, see: :first-child
, :not
, and the adjacent sibling selector (+
).