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:
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:
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:
Using JavaScript or jQuery
When a CSS solution is not feasible or too complex, style the first match from script:
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.
| Feature | CSS Selector | Use Case |
| First element of type | :first-of-type | Select 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 JavaScript | querySelector() | Programmatically style the first element with the specified class. |
Related reading
System design interview problems on this topic
- Design Google Doc: solution and walkthrough
- Design Facebook Messenger: solution and walkthrough
- Design Typeahead Suggestion: solution and walkthrough
- Design an Online Presence Indicator Service: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseData 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.