css:nth-​​child():之后

roc*_*ier 24 html css css-selectors css3

有可能混合:nth-child()after

我有<ol>一些项目,我想添加一些文字:after.这很好,但我想在第1,第2和第3项以及第4,第5和第6项上有不同的文字.

使用下面的代码,我最终会得到每个li粉红色的"大号".

这对我来说没有意义,但我是这个nth-childmalarky的新手.

data.html

<ol id="id" class="ui-sortable">
    <li>
        <p>Bacon</p>
    </li>
    <li>
        <p>Bacon</p>
    </li>
    <li>
        <p>Bacon</p>
    </li>

    <!.. repeats -->

    <li>
        <p>Bacon</p>
    </li>
</ol> 
Run Code Online (Sandbox Code Playgroud)

pretty.css

#id li p:after {
    float: right;
    content: 'nom';
}

#id li p:nth-child(1):after,
#id li p:nth-child(2):after,
#id li p:nth-child(3):after {
    content: 'OM';
    color: pink;
}

#id li p:nth-child(4):after,
#id li p:nth-child(5):after,
#id li p:nth-child(6):after {
    content: 'Nom';
    color: blue;
}
Run Code Online (Sandbox Code Playgroud)

我真的不想用js这样做,因为它只是一个'很好的'功能.

我只担心新的浏览器,所以不需要oldIE等的变通方法.

Gab*_*oli 32

你可以,但你做错了..

所有p元素都在里面的问题li.所以他们都是他们li容器的第一个孩子.

你需要把元素放在nth-child上面li.

#id li:nth-child(1) p:after,
#id li:nth-child(2) p:after,
#id li:nth-child(3) p:after {
    content: 'OM';
    color: pink;
}

#id li:nth-child(4) p:after,
#id li:nth-child(5) p:after,
#id li:nth-child(6) p:after {
    content: 'Nom';
    color: blue;
}
Run Code Online (Sandbox Code Playgroud)

引用W3C文档

:nth-child(an+b)伪级符号代表具有一个+ B-1的元素的兄弟姐妹之前它在文档树中,对于任意的正整数或正的零值,并具有父元素.


更新1

你也可以通过使用来简化这个

#id li:nth-child(-n+3) p:after {
    content: 'OM';
    color: pink;
}

#id li:nth-last-child(-n+3) p:after { /*this means last 3*/
    content: 'Nom';
    color: blue;
}
Run Code Online (Sandbox Code Playgroud)

演示http://jsfiddle.net/gaby/4H4AS/2/


更新2

如果你想要前六个只是不同(而不是前三个和后三个)你可以

#id li:nth-child(-n+6) p:after { /*this means first 6*/
    content: 'Nom';
    color: blue;
}

#id li:nth-child(-n+3) p:after {/*this means first 3 and since it comes second it has precedence over the previous for the common elements*/
    content: 'OM';
    color: pink;
}
Run Code Online (Sandbox Code Playgroud)

演示http://jsfiddle.net/gaby/4H4AS/3/


rai*_*7ow 7

应该这样做:

#id li:nth-child(1) p:after,
#id li:nth-child(2) p:after,
#id li:nth-child(3) p:after {
    content: 'OM';
    color: pink;
}
#id li:nth-child(4) p:after,
#id li:nth-child(5) p:after,
#id li:nth-child(6) p:after {
    content: 'Nom';
    color: blue;
}
Run Code Online (Sandbox Code Playgroud)

JS小提琴.

... <p>始终<li>是所示HTML结构中的第一个子节点.

但请注意,content: 'nom';第一个样式定义中的规则被覆盖(但"浮动"规则):对于':after'伪元素和其他元素一样,它是相同的级联裁定.)