16

What is the syntax for selecting the first element with a certain class? Please specify whether that method of selection is part of CSS3 or CSS2.1.

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
Web_Designer
  • 72,308
  • 93
  • 206
  • 262

4 Answers4

59

If you need the first element with a certain class among its siblings, you can use

.myclass {
    /* styles of the first one */
}

.myclass ~ .myclass {
    /* styles of the others (must cancel the styles of the first rule) */
}

Don't try to use .myclass:not(.myclass ~ .myclass) to do this in only one rule, it won't work since :not() only accepts simple selectors in the parentheses.

If you want the first .myclass in the whole document, there is no way to do it with CSS alone.

The :nth-of-type() or :nth-child() approaches posted are wrong, even if they coincidentally happen to match the elements you want in your page.

Browser support of sibling selector (~): IE7+ and all others.

Lea Verou
  • 23,618
  • 9
  • 46
  • 48
  • 3
    Browser support is actually better than the CSS structural pseudoclasses. Edited my answer to include it. – Lea Verou Mar 14 '11 at 00:11
  • Fail me... I just realized I had thought of this myself some time after you posted this, completely forgetting about your answer. I've credited you here now: http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class/8539107#8539107 – BoltClock May 10 '12 at 08:39
  • 1
    do you know for the last element with the same class? – Johhan Santana Nov 05 '15 at 18:21
  • you save my day man, thanks!! just in case, instead of override, you can select the first one like this: .myclass:not(.myclass ~ .myclass) – mauriblint Sep 07 '22 at 09:47
0

This problem sucks as bad as the solutions. IMO you should just give the first element a class of .first{} programmatically.

Spankied
  • 1,626
  • 13
  • 21
-1

Try this

.testparent .test:first-child {
    color: red;
}

<div class="testparent">
<div class="test">test</div>
<div class="test">test</div>
<div class="test">test</div>
</div>

the first div 'test' has red color only.

ngduc
  • 1,415
  • 12
  • 17
-2
.class-name:first-of-type {
  ⋮ declarations
}
Druid
  • 6,423
  • 4
  • 41
  • 56
  • 6
    The `:first-of-type` selector applies to element names, not class names: https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type – Web_Designer Jun 16 '13 at 22:08