Vic
Vic

Reputation: 8961

css selector for first child element

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.

Upvotes: 2

Views: 5321

Answers (2)

MRadev
MRadev

Reputation: 431

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/

Upvotes: 0

Sampson
Sampson

Reputation: 268334

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.

Upvotes: 12

Related Questions