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 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:Previous drafts used a new pseudo-class,
:nth-match()
, so you may see that syntax in some discussions of the feature: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.
This it not possible to use the CSS3 selector :first-of-type to select the first element with a given class name.
However, if the targeted element has a previous element sibling, you can combine the negation CSS pseudo-class and the adjacent sibling selectors to match an element that doesn't immediately have a previous element with the same class name :
Full working code example:
I found a solution for your reference. from some group divs select from group of two same class divs the first one
BTW, I don't know why
:last-of-type
works, but:first-of-type
does not work.My experiments on jsfiddle... https://jsfiddle.net/aspanoz/m1sg4496/
This is an old thread, but I'm responding because it still appears high in the list of search results. Now that the future has arrived, you can use the :nth-child pseudo-selector.
The :nth-child pseudo-selector is powerful - the parentheses accept formulas as well as numbers.
More here: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
Not sure how to explain this but I ran into something similar today. Not being able to set
.user:first-of-type{}
while.user:last-of-type{}
worked fine. This was fixed after I wrapped them inside a div without any class or styling:https://codepen.io/adrianTNT/pen/WgEpbE
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:Explanations and illustrations for the workaround are given here and here.