Question
Answer and Explanation
To select the first element with a specific class using CSS, you can leverage the :first-of-type
pseudo-class combined with a class selector. Here's how it works:
Understanding :first-of-type
:
- The :first-of-type
pseudo-class selects the first element of a particular type within its parent. Importantly, it looks at the element type (e.g., div
, p
, span
) and not at classes or IDs.
- When you combine it with a class selector, you can target the first element that has both the matching class and is the first of that element type.
Using :first-of-type
with Class Selectors:
- To select the first element with a specific class, you should first apply your class selector then follow it by the pseudo-class. For example, to target the first div
element with the class .my-class
, you would use: div.my-class:first-of-type
.
CSS Example:
/ Selects the first <p> element with class "example-text" /
p.example-text:first-of-type {
color: blue;
font-weight: bold;
}
Important Considerations:
- Element Type Matters: If you have multiple element types with the same class, :first-of-type
will select the first of each type. If you want to select the first element with class, regardless of type, it is usually better to select the parent element and use :first-child
selector like this: .parent > :first-child
and add a class to parent.
- Specificity: Remember CSS specificity rules. More specific selectors (e.g. using IDs) will take precedence.
- Browser Compatibility: The :first-of-type
selector is widely supported in modern browsers.
By combining the class selector with :first-of-type
, you gain precise control over styling the initial element of a specific type that matches your desired class within its container. This can be useful for layouts where you need unique styling for a section's first element.