Home >Web Front-end >CSS Tutorial >Can :first-of-type Select the First Element with a Specific Class Name?
Using :first-of-type Selector with Class Name
Question:
Can the CSS3 selector :first-of-type be used to select the first element with a specific class name?
Answer:
No, it is not possible to use :first-of-type alone to select the first element with a particular class.
Explanation:
The :first-of-type pseudo-class targets the first element of its type among its siblings. Adding a class selector or a type selector to this pseudo-class indicates that the selection should be restricted to elements within a specific type (e.g., div or p) that also have the given class name. However, CSS does not provide a dedicated :first-of-class selector that selects only the first occurrence of a class.
Workaround:
As a workaround, you can achieve this functionality by using a combination of class names and selector specificity:
Example:
.myclass1 { color: red; } .myclass1 ~ .myclass1 { color: /* default, or inherited */; }
This ensures that only the first element with the class .myclass1 receives the specified style, while subsequent elements inherit the default or parent style.
Additional Notes:
The above is the detailed content of Can :first-of-type Select the First Element with a Specific Class Name?. For more information, please follow other related articles on the PHP Chinese website!