6

Is there a CSS selector for the first instance of a child with class? For example, take this code:

<div id="container">
    <div class="nothing">
    </div>
    <div class="child"> <!-- SELECT THIS ONE -->
    </div>
    <div class="child"> <!-- NOT THIS ONE -->
    </div>
    <div class="child"> <!-- NOT THIS ONE -->
    </div>
</div>

Is there a css selector to style the first occurrence of a div with class "child"?

6
  • 1
    There isn't a CSS selector, but there is a jQuery selector. Commented Aug 21, 2013 at 16:22
  • What have you tried? Have you had a look at api.jquery.com/category/selectors, which lists all the selectors that jQuery understands? Personally, I would just use $('.child').first(). Commented Aug 21, 2013 at 16:22
  • 1
    No, there is no such selector using CSS. The closest thing is the :first-of-type selector, but that only matches by tag name, not class Commented Aug 21, 2013 at 16:22
  • Doh - that's unfortunate. thanks for the responses Commented Aug 21, 2013 at 16:23
  • If you're looking for a CSS solution, then this is a duplicate. You can't do this with a single selector but there is a workaround that you might be able to use. See the link. Commented Aug 21, 2013 at 16:28

2 Answers 2

10

You could style .child and revert styles for subsequent .child siblings using the subsequent-sibling combinator, ~:

.child {
  color: #ff0000;
}
.child ~ .child {
  color: inherit;
}
<div id="container">
  <div class="nothing">nothing
  </div>
  <div class="child">SELECT THIS ONE
  </div>
  <div class="child">NOT THIS ONE
  </div>
  <div class="child">NOT THIS ONE
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

or even better reset the color to inherit and it will return to default!
-2

You can use the ":nth-child" css selector.

DEMO: http://jsfiddle.net/2pyvz/

CSS:

.child:nth-child(2) { color:red; }

6 Comments

Doesn't work: jsfiddle.net/fkling/Pex2R. Reason: :first-child selects the element if and only if it is the first child of its parent. In the OP's example, div.nothing is the first child though.
Yeah, doesn't work for me either
I updated the answer. Like previously mentioned :first-child only works on the first child of the its parent. See if :nth-child works for you.
.child:nth-child(2) selects the second child of its parent, not the first .child element. While it might work in this specific situation, it is not a solution to actual question.
:nth-of-type will only select the nth of the same type of element. Being that in the example given the first child is a div element you can't use :nth-of-type to select the first one.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.