2

Let's say my html looks like this:

<div class="container">
    <... some html here ...>
</div>

I want to get the first direct child of .container.

I could do .container > div:first-child but that's assuming the it is a div which is not always the case.

1
  • 6
    .container > :first-child without the div portion.
    – Sampson
    Commented Jan 22, 2014 at 14:31

2 Answers 2

12

Use the :first-child pseudo-class without a tagname:

.container > :first-child

This will grab any element that is the immediate first child, regardless of its tagname. This is similar to the way in which we use other pseudo-classes such as :hover which alone targets any element, while a:hover targets only the hover state of anchors.

2
  • Could I ask a simple add-on question to your answer? Using your code in a Fiddle, like so, I don't see any CSS reflected. But, here (note the omitted >), I do. Sorry to tag along, I'm just curious.
    – Nick
    Commented Jan 22, 2014 at 14:38
  • :first-child doesn't target textNodes. You need to have an element within the container jsfiddle.net/jonathansampson/xkX95/5
    – Sampson
    Commented Jan 22, 2014 at 14:39
0

Not using the element itself, but a class is a better solution and way more semantic for so many reasons.

And give the class to the children of the element, not only the container like this:

HTML:

<article class="container">
  <p class="blah">First paragraph...</p>
  <p class="blah">Lorem ipsum...</p>
  <p class="blah">Dolor sit amet...</p>
</article>

CSS:

.blah {
    background: red;
    color: white;
}

.blah:first-child {
    background: #000;
}

You can see it in action here: http://jsfiddle.net/Roobyx/ygP4B/

4
  • 1
    (Jonathan Sampson's answer wont work..) Are you sure? fiddle
    – Mr_Green
    Commented Jan 22, 2014 at 14:57
  • Really not much of a reason to give it a class when you can just target it like so, .container p { }. jsfiddle.net/ygP4B/1 Commented Jan 22, 2014 at 14:57
  • @JoshPowell Mentioning class always is a better suggestion.. unless if you can't change the HTML. In my opinion, this is a good suggestion.
    – Mr_Green
    Commented Jan 22, 2014 at 14:59
  • @Mr_Green I would normally agree with you as well. In this case you are adding more to the html that isn't necessary needed. Is his option good, heck yeah it is but when you are using a setup like that, I personally, find it more efficient to target them with a general selector. He can also use the selector like so, .container > p { } to only select the direct descendants of the parent. Commented Jan 22, 2014 at 15:13

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.