Home > Enterprise >  How do I use CSS to select the first instance of a specific class?
How do I use CSS to select the first instance of a specific class?

Time:01-12

I have a class that appears multiple times in a page, each time in it's own separate div. I want to select only the first instance of this class.

Example:

<div >
  <div >
    First Line
  </div>
</div>

<div >
  <div >
    Second Line
  </div>
</div>

I tried using .line:first-child, .line:first-of-type, and .line:nth-of-type(1) but came to understand that each instance of .line will be selected since they are always the first child of the parent of .line.

CodePudding user response:

Detecting the first .container element will work in your specific example but could not be enough:

if you have some other elements before the first .container (e.g. a heading), a selector looking for .container:first-child won't work: you need to also detect the immediate .container sibling after a :not(.container) element, so it's better to declare both the selectors

:not(.container)   .container .line,
.container:first-child .line {
  color: yellowgreen
}
<h1>Title (optional)</h1>

<div >
  <div >
    First Line
  </div>
</div>

<div >
  <div >
    Second Line
  </div>
</div>

CodePudding user response:

If you want to select only the first class in one of the containers. you can use the :first-child for that specific container and .line after that like this: .container:first-child .line

Example:

.container:first-child .line {
background-color:red;
}
<div >
  <div >
    First Line
  </div>
</div>

<div >
  <div >
    Second Line
  </div>
</div>

CodePudding user response:

You can create different classes to avoid confusion amongst the code, or use a bit of javascript to do the same thing.

If you use the following:

document.querySelector(".container") 
document.querySelector(".line")

Since multiple items will satisfy this requirement, then it will access only the first occurrence of either of the two classes. Then you can use a variety of methods to obtain the change you want in those two classes.

  • Related