CSS selector for first element with class
Asked 07 September, 2021
Viewed 1.1K times
  • 50
Votes

I have a bunch of elements with a class name red, but I can't seem to select the first element with the class="red" using the following CSS rule:

.home .red:first-child {
    border: 1px solid red;
}
<div class="home">
    <span>blah</span>
    <p class="red">first</p>
    <p class="red">second</p>
    <p class="red">third</p>
    <p class="red">fourth</p>
</div>

What is wrong in this selector and how do I correct it to target the first child with class red?

20 Answer