CSS
Web Development
HTML
Programming
CSS Selectors

CSS selector for the first element with a class

Codemia Knowledge Hub ·

CSS has no pseudo-class that targets the first element with a given class. You can combine the class with :first-of-type or :nth-of-type() when the document structure allows it, or fall back to JavaScript. This comes up when several elements share a class and only the first occurrence should be styled differently.

CSS can select and style elements by their attributes, classes, types and positions, but "first with this class" is not one of the built-in conditions, so each workaround below depends on how your markup is arranged.

Class selectors

A class selector targets elements by their class attribute:

css
.myclass {
    color: red;
}

This gives every element with class="myclass" red text.

Using :first-of-type

When the target elements share a tag, combine the class selector with :first-of-type:

html
<div class="content">This is the first div with class 'content'.</div>
<div class="content">This is the second div with class 'content'.</div>
css
.content:first-of-type {
    font-weight: bold;
}

This makes the first .content div bold. It only works if no other element of the same type comes before it in the same container.

Using :nth-of-type()

When elements of different types share the class, use :nth-of-type() with a selector that matches both the element type and the class:

html
<div class="item">Not this!</div>
<p class="item">Style this first paragraph with 'item' class.</p>
<p class="item">Another paragraph.</p>
css
p.item:nth-of-type(1) {
    color: green;
}

Using JavaScript or jQuery

When a CSS solution is not feasible or too complex, style the first match from script:

javascript
document.querySelector('.item').style.color = 'blue';  // Pure JavaScript
$('.item').first().css('color', 'blue');  // jQuery

Typical uses are highlighting the first item in a list of products or news articles, or giving the first testimonial in a section a distinct style.

FeatureCSS SelectorUse Case
First element of type:first-of-typeSelect the first element of its type with the specified class.
Specific occurrence:nth-of-type()Target a specific occurrence of an element with the specified class.
With JavaScriptquerySelector()Programmatically style the first element with the specified class.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms