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

时间:2012-12-19 17:07:30

标签: html css css3 css-selectors

是否可以混合:nth-child()after

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

使用以下代码,我最终会得到li每个{&#39;大&#39;在它之后粉红色。

这对我来说没有意义,但我是这位nth-child malarky的新手。

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> 

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;
}

我真的不喜欢用js这样做,因为它只是一个很好的拥有&#39;特征

我只担心新的浏览器,因此不需要oldIE等的解决方法。

3 个答案:

答案 0 :(得分:30)

你可以,但是你做错了..

所有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;
}

引用the W3C documentation

  

:nth-child(an+b)伪类表示法表示在文档树中具有+ b-1 兄弟姐妹的元素,对于n的任何正整数或零值,并且具有父元素。


更新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;
}

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

演示

更新2

如果您希望前六个不同(而不是前3个和后3个),您可以

#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;
}

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

演示

答案 1 :(得分: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;
}

JS Fiddle.

...因为<p>始终是显示的HTML结构中<li>的第一个孩子。

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

答案 2 :(得分:0)

您可以像这样组合伪装...

#id li:nth-child(1)::before {
    border-left-color: red;
}
#id li:nth-child(2)::before {
    border-left-color: white;
}
#id li:nth-child(3)::before {
    border-left-color: blue;
}