2

I have the following markup:

<div class="a"></div>
<div class="b"></div> <!-- :first -->
<div class="b"></div>
<div class="b"></div> <!-- :last -->
<div class="c"></div>

I'm trying to target the first and last <div> with class b. If I was using jQuery selectors for this, .b:first and .b:last would do the trick.

However with CSS, that's tricky: the first <div class="b"> is located after another <div> with a different class, and both :first-child and :first-of-type match the first <div>, with class a.

Is there a selector targeting the first of the items matching the class?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • possible duplicate of [display first of class type](http://stackoverflow.com/questions/6407907/display-first-of-class-type) – Ry- Sep 12 '12 at 00:00
  • Not *quite* what you're looking for, but the [nth-child](http://www.w3schools.com/cssref/sel_nth-child.asp) might be of interest? – Patrick Sep 12 '12 at 00:02
  • @Patrick nope, same as `first-child` and `last-child`, but with an arbitrary number. – BenMorel Sep 12 '12 at 00:14

2 Answers2

4

No, there is no equivalent CSS selector to jQuery's :first or :last selector, because those selectors are filters, and not true simple selectors by the CSS definition.

In Selectors 3 there is no :first-of-class or similar selector either.

However, you can use overriding rules with the ~ combinator to apply styles to the first child of a certain class:

But there is currently no way to apply styles to the last child of a certain class using CSS:

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
0

You can always but a wrapper around the divs with the b class also, and target the contents of that using the :first-child and :last-child selectors.

See example here: http://cssdesk.com/fYTHF

streetlight
  • 5,968
  • 13
  • 62
  • 101