简体   繁体   中英

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

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

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM