To select the first element with a specific class in CSS, you can use the :first-of-type pseudo-class in combination with the class selector.
For example, if you have multiple elements with the class "example-class", you can select the first one like this:
.example-class:first-of-type {
/* styles for the first element with class "example-class" */
}
You can also use :first-child pseudo-class to select first child with that class.
..parent > .example-class:first-child {
/* styles for the first child with class "example-class" inside .parent element*/
}
You can also use :nth-of-type(n) to select nth element with that class.
..example-class:nth-of-type(1) {
/* styles for the first element with class "example-class" */
}
You can also use :nth-child(n) to select nth child with that class.
..parent > .example-class:nth-child(1) {
/* styles for the first child with class "example-class" inside .parent element*/
}
Note that :first-of-type only selects the first element of its type among its siblings. The :nth-of-type and :nth-child pseudo-classes allow you to select an element based on its position among its siblings, counting from the first element of that type or any element respectively.
Comments (0)