Selecting only the first element occurrence out of siblings with the same class name with CSS3

Imagine you have the following markup…

<ul>
    <li>item 0</li>
    <li>item 1</li>
    <li class="marked">item 2</li>
    <li class="marked">item 3</li>
    <li class="marked">item 4</li>
</ul>

… And you need to apply special styles only to the first occurence of the .selected class. CSS3 has a lot of possibilities for selecting elements, but it does not provide solution for this case. So, when :nth-of-type(), :first-of-type, nth-child() and :first-child do not work, you can use this one:

/* select any .marked element */
.marked {
    color: #f00;
}

/* override all .marked elements but the first using the sibling selector */
.marked ~ .marked {
    color: #000;
}

Related Posts

About these ads

22 comments

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s