Home >Web Front-end >CSS Tutorial >Can CSS3's `:first-of-type` Selector Target the First Instance of a Specific Class?

Can CSS3's `:first-of-type` Selector Target the First Instance of a Specific Class?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 14:41:09692browse

Can CSS3's `:first-of-type` Selector Target the First Instance of a Specific Class?

Can CSS3 :first-of-type Selector Target Specific Class Names?

While the CSS3 :first-of-type selector can select the first element of a specific type (e.g., div, p), it cannot be used independently to target the first occurrence of a class name. This is because using a class selector (or type selector) with :first-of-type means selecting an element that:

  • Has the specified class (or type)
  • Is the first element of its type among its siblings

However, there is no inherent :first-of-class selector in CSS that exclusively selects the first instance of a class.

Workaround

To achieve this functionality, a workaround can be employed:

.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default or inherited from parent */; }

This workaround utilizes the adjacent sibling combinator (~) to style all occurrences of .myclass1 except the first. The first .myclass1 will inherit its color from its parent div (or default to browser defaults).

For further insights and visual illustrations on this workaround, refer to:

  • [W3Schools: Using Child and Sibling Selectors](https://www.w3schools.com/css/sel_combinators.asp)
  • [CSS Tricks: Styling the First Sibling](https://css-tricks.com/styling-first-sibling/)

The above is the detailed content of Can CSS3's `:first-of-type` Selector Target the First Instance of a Specific Class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn