Selecting the First Occurrence of a Class Within a Parent
In CSS, the challenge arises when you need to target the first element of a specific class within a parent element, especially when the class may appear in varying positions within its siblings. This issue becomes even more complex when the parent element's class or child structure may differ.
The :first-of-type Pseudo-Class
CSS3 offers the :first-of-type pseudo-class, which allows you to select the first element of a specific type within its siblings. However, there is no equivalent :first-of-class pseudo-class specifically for selecting the first element of a given class.
A Workaround Using ~ and General Sibling Selector
One workaround is to use the general sibling combinator (~) along with an overriding rule. By knowing the default styles applied to other elements with the same class, you can create a more specific rule that overrides the default styles only for the elements that follow the first occurrence of the target class.
Example:
.parentClass > * > .targetClass { /* Apply styles to all .targetClass elements within .parentClass */ } .parentClass > * > .targetClass ~ .targetClass { /* Apply overriding styles only to .targetClass elements that follow */ }
Illustration:
Consider the following HTML structure:
...First targetSecond targetThird target
In this scenario, the first rule would apply styles to all elements with class "targetClass" inside the "parentClass" element. The second rule would override those styles for all "targetClass" elements that follow the first one, reverting any custom styles applied by the first rule.
Browser Compatibility:
The general sibling combinator (~) is recognized by IE7 and later. Therefore, this workaround is compatible with all major browsers except IE6.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3