15

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
  • 23,524
  • 7
  • 119
  • 253
Web_Designer
  • 68,768
  • 89
  • 200
  • 259

4 Answers4

55

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,130
  • 9
  • 44
  • 47
  • 2
    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
0

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

Spankied
  • 1,218
  • 9
  • 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,377
  • 10
  • 16
-2
.class-name:first-of-type {
  ⋮ declarations
}
Druid
  • 6,348
  • 3
  • 38
  • 53
  • 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