Home > Web Front-end > CSS Tutorial > Can I Use CSS3's `:first-of-type` Selector with Class Names?

Can I Use CSS3's `:first-of-type` Selector with Class Names?

DDD
Release: 2025-01-02 13:14:38
Original
804 people have browsed it

Can I Use CSS3's `:first-of-type` Selector with Class Names?

Using CSS3 Selector :first-of-type with Class Names

One may wonder if it is possible to utilize the CSS3 selector :first-of-type in conjunction with a class name. However, using only this selector alone may not suffice.

Explanation

The :first-of-type pseudo-class targets the first element of a specific type within its siblings. When combined with a class selector, it filters for elements that both possess the specified class and are the first element of their type among their siblings.

Unfortunately, CSS does not have a :first-of-class selector that solely finds the first occurrence of an element with a particular class.

Workaround

To work around this limitation, one can employ the following technique:

.myclass1 {
  color: red;
}

.myclass1 ~ .myclass1 {
  color: /* default or inherited from parent div */;
}
Copy after login

Explanation

This workaround uses the general sibling combinator (~) to target all elements with the class myclass1 that are preceded by another element with the same class. By setting the color of these subsequent elements to default or inherited from the parent div, we effectively suppress the red color for all but the first occurrence of .myclass1.

Additional Resources

More detailed explanations and visual illustrations of this workaround can be found here:

  • [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#Adjacent_sibling_selectors)
  • [CSS Tricks](https://css-tricks.com/almanac/selectors/c/combinators/#:~:text=The ~ combinator selects all,= 30 (class has specificity))

The above is the detailed content of Can I Use CSS3's `:first-of-type` Selector with Class Names?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template