为最后一个孩子留下最后的孩子

时间:2013-09-23 17:09:47

标签: javascript html css css3 css-selectors

我有以下HTML:

<section></section>

<section id="top">
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>   <!-- STYLE THIS -->
        <li>5</li>   <!-- STYLE THIS -->
    </ul>
</section>

<section></section>

我已动态生成HTML,如何设置上述两种风格?使用section将样式应用于id="top",并为最后list-items中的最后2 ul设置样式。

3 个答案:

答案 0 :(得分:8)

这样的东西?

#top > ul:last-of-type li:nth-last-child(-n+2) {
    background:aqua;
}

jsFiddle here

使用选择器组合 - :last-of-type:nth-last-child

注意 - 这是IE8及以下的not fully supported

答案 1 :(得分:2)

怎么样:

#top > ul:nth-child(3) > li:nth-child(4),
#top > ul:nth-child(3) > li:nth-child(5) {}

Working demo

答案 2 :(得分:1)

#top {
    color:red;
}

#top ul:last-of-type li:last-of-type {
    color:green;
}