user1346765
user1346765

Reputation: 122

First-child pseudo-class in css 2.1

I don't know where to put pseudo class in this definition:

#recently_played_grid li img {
    margin-left: 10px;
}

I want to set margin-left to 0px just in a first child of the list. Should I do:

#recently_played_grid li:first-child img

?

It doesn't seem to work

Upvotes: 0

Views: 260

Answers (3)

Last Rose Studios
Last Rose Studios

Reputation: 2481

What do you want to accomplish?

If you are trying to create an image gallery, and every image is in a list item, then what you might want to do instead is put a negative margin on the <ul> to counter the margin on the first <li>, and by extension every <li> that is in the first 'column'

Upvotes: 0

reggaemahn
reggaemahn

Reputation: 6668

If what you are looking for is to have ALL the images in the first li item then your code should work fine. If you are looking to have a margin on the first img child of every li then you'll have to change it to

#recently_played_grid li img:first-child

<ul>
    <li>
        <img />                    << Selects this, and
        <img />
        <img />
    </li>
    <li>
        <img />                     << Selects this, and
        <img />
        <img />
    </li>
    <li>
        <img />                     << Selects this
        <img />
        <img />
    </li>
</ul>

If you want only the FIRST img in the FIRST li then you should change it to

#recently_played_grid li:first-child img:first-child


<ul>
    <li>
        <img />                          << Selects only this
        <img />
        <img />
    </li>
    <li>
        <img />
        <img />
        <img />
    </li>
    <li>
        <img />
        <img />
        <img />
    </li>
</ul>

Further reading here http://www.w3.org/TR/CSS2/selector.html#pseudo-class-selectors

Upvotes: 3

Matthew R.
Matthew R.

Reputation: 4350

It depends on what you are trying to target. If it is the first <li> your selector should be:

#recently_played_grid li:first-child img { ... }

If you are trying to target the first image:

#recently_played_grid li img:first-child { ... }

The reason your margin isn't working may be that your element is set to be inline or you may be experiencing margin collapse. Try adding a background color or something to see if your selector is working. This should help you target the issue.

Also, if you are worried about cross-browser, older versions of IE don't support structural pseudo selectors. I usually use something like Selectivizr as a polyfill.

Upvotes: 0

Related Questions