Sami A. Sami A. - 2 months ago 12
CSS Question

How can select first child/last child of class in a mixed container?

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?

Answer

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' });
Comments