css :nth-child() :after
:nth-child()
和 after
可以混用吗?
我有一个 <ol>
项目,我想在 :after
之后添加一些文本.这很好用,但我希望在第 1、第 2 和第 3 项以及第 4、第 5 和第 6 项上使用不同的文本.
I have an <ol>
of items and I want to add some text :after
. This works fine but I'd then like to have different text on 1st, 2nd and 3rd items and then 4th, 5th and 6th as well.
使用下面的代码,我最终得到每个 li
后面都有粉红色的大".
With the below code I end up with every li
having 'large' in pink after it.
这对我来说没有意义,但是我是这个 nth-child
的新手.
This doesn't make sense to me however I am new to this 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 来做这件事,因为它只是一个很高兴拥有"的功能.
I'd really like not to do this with js as it just a 'nice to have' feature.
我只担心新的浏览器,所以不需要 oldIE 等的解决方法.
I'm only worried about new browsers so no need for workarounds for oldIE etc.
推荐答案
你可以,但是你做错了..
You can, but you are doing it wrong..
所有 p
元素都在 li
内的问题.所以他们都是他们的 li
容器的第一个孩子.
The issue that that all your p
elements are inside li
. So all of them are the first child of their li
container.
您需要将 nth-child
放在 li
元素上.
You will need to put the nth-child
on the li
elements.
#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;
}
<小时>
引用W3C 文档
:nth-child(an+b)
伪类表示法表示在文档树中具有一个+b-1 个兄弟的元素,例如n 的任何正整数或零值,并且具有父元素.
The
:nth-child(an+b)
pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element.
<小时>
更新 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 个),您可以
If you want the first six only to be different (and not first 3 and last 3) you could
#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/
相关文章