Home > Web Front-end > CSS Tutorial > Can I Use the :first-of-type Selector to Select the First Element with a Specific Class?

Can I Use the :first-of-type Selector to Select the First Element with a Specific Class?

Barbara Streisand
Release: 2024-12-29 17:11:10
Original
281 people have browsed it

Can I Use the :first-of-type Selector to Select the First Element with a Specific Class?

:first-of-type Selector and Class Selection

The :first-of-type selector in CSS3 is designed to select the first element of a specific type (e.g., p, div, etc.) among its siblings. However, a common misconception arises when attempting to use it in conjunction with a class name.

Question:

Is it possible to utilize the :first-of-type selector to select the first element with a particular class name?

Answer:

Unfortunately, it is not possible to achieve this using a single selector. The :first-of-type pseudo-class operates on element types, not class names. Using a class selector with it means selecting elements that have the specified class and are also the first of their type within their sibling group.

Workaround:

As there is no :first-of-class selector provided by CSS, a workaround can be used to target the first occurrence of a class:

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

Here, the first class declaration sets the color of all elements with the "myclass1" class to red. The subsequent declaration targets any element with the "myclass1" class that is immediately preceded by another element with the same class. This latter declaration resets the color to its default or inherited value for all except the first occurrence of the class.

Detailed explanations and illustrations of this workaround can be found in the following articles:

  • https://css-tricks.com/the-problem-with-first-child-selector/
  • https://www.quirksmode.org/css/contents.html#first-of-type-sibling

The above is the detailed content of Can I Use the :first-of-type Selector to Select the First Element with a Specific Class?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template