Sven
Sven

Reputation: 13275

CSS: Child combinator selector & :first-child?

I have a div with some other divs, some paragraphs and some images in it. It basically looks like this:

<div id="parent">
    <div>
        This image is inside a div.
        <img src="http://www.placehold.it/100" alt="" />
    </div>
    <p>
        And this inside a paragraph.
        <img src="http://www.placehold.it/100" alt="" />
    </p>
    <img src="http://www.placehold.it/100" alt="" />
    <img src="http://www.placehold.it/100" alt="" />
</div>

Now I only want to select the images that aren't nested inside another div or p. I am doing this using the child combinator selector:

#parent > img {
    border: 1px solid red;
}

This works, but now I only want to select the first, non-nested image. I tried it like this, but without any result:

#parent > img:first-child {
    border: 1px solid blue;
}

http://jsfiddle.net/vF2DU/

How do I do it? Is there a way without adding a class or id like #first?

Upvotes: 1

Views: 1892

Answers (2)

dsgriffin
dsgriffin

Reputation: 68596

You could use the first-of-type or the nth-of-type selectors.

In this case, first-of-type is probably more relevant, but I'll show you the syntax for both below:


About first-of-type:

"The :first-of-type selector matches every element that is the first child, of a particular type, of its parent."

first-of-type example:

#parent > img:first-of-type {
    border: 1px solid blue;
}

Here is a working jsFiddle for first-of-type in regard to your use case.


About nth-of-type:

"The :nth-of-type(n) selector matches every element that is the nth child, of a particular type, of its parent. n can be a number, a keyword, or a formula."

nth-of-type example:

#parent > img:nth-of-type(1) {
    border: 1px solid blue;
}

Here is a working jsFiddle for nth-of-type in regard to your use case.


Support:

Both are supported in all major browsers - Chrome, Firefox, Opera and Internet Explorer (IE9 and above). If you're interested in getting them to work perfectly in IE8 and before, check out Selectivizr.

Upvotes: 7

nd_macias
nd_macias

Reputation: 812

:first-child means first-child, not first encountered element of a type. What you need is :first-of-type selector. working example

Upvotes: 5

Related Questions