Home >Web Front-end >CSS Tutorial >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:
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:
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!