Is it possible to use the CSS3 selector :first-of-type
to select the first element with a given class name? I haven't been successful with my test so I'm thinking it's not?
The Code (http://jsfiddle.net/YWY4L/):
p:first-of-type {color:blue}
p.myclass1:first-of-type {color:red}
.myclass2:first-of-type {color:green}
<div>
<div>This text should appear as normal</div>
<p>This text should be blue.</p>
<p class="myclass1">This text should appear red.</p>
<p class="myclass2">This text should appear green.</p>
</div>
The :first-of-type selector in CSS allows you to target the first occurence of an element within its container. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
CSS - The :first-child Pseudo-class The :first-child pseudo-class matches a specified element that is the first child of another element.
The selector must start with a period ( . ) and then the class name. The browser will look for all tags in the page that have a class attribute containing that class name. The spelling and casing must be exactly the same - .
The draft CSS Selectors Level 4 proposes to add an of <other-selector>
grammar within the :nth-child
selector. This would allow you to pick out the nth child matching a given other selector:
:nth-child(1 of p.myclass)
Previous drafts used a new pseudo-class, :nth-match()
, so you may see that syntax in some discussions of the feature:
:nth-match(1 of p.myclass)
This has now been implemented in WebKit, and is thus available in Safari, but that appears to be the only browser that supports it. There are tickets filed for implementing it Blink (Chrome), Gecko (Firefox), and a request to implement it in Edge, but no apparent progress on any of these.
No, it's not possible using just one selector. The :first-of-type
pseudo-class selects the first element of its type (div
, p
, etc). Using a class selector (or a type selector) with that pseudo-class means to select an element if it has the given class (or is of the given type) and is the first of its type among its siblings.
Unfortunately, CSS doesn't provide a :first-of-class
selector that only chooses the first occurrence of a class. As a workaround, you can use something like this:
.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }
Explanations and illustrations for the workaround are given here and here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With