在不使用 javascript 的情况下使用 n-th child 时,有没有办法访问 n?
Is there a way to access n when using n-th child without javascript?
比如说我有:
#with-index span::after {
content: attr(data-n);
position: relative;
top: -8px;
font-size: 9px;
font-weight: bold;
color: red;
}
#without-index span:nth-child(1n)::after {
content: attr(n);
position: relative;
top: -8px;
font-size: 9px;
font-weight: bold;
color: red;
}
<div id="without-index">
<span>Hello</span> <span>World</span>
</div>
<div id="with-index">
<span data-n="0">Hello</span> <span data-n="1">World</span>
</div>
如果我把索引作为一个属性,我可以使用content: attr(data-n)
。如果有一种方法可以使用 nth-child(1n)
获取 n
的值来达到相同的效果而无需设置任何其他属性?
您可以像这样使用 CSS 计数器:
#without-index { counter-reset: number -1; }
#without-index span::after {
content: counter(number);
counter-increment: number;
position: relative;
top: -8px;
font-size: 9px;
font-weight: bold;
color: red;
}
<div id="without-index">
<span>Hello</span> <span>World</span>
</div>
比如说我有:
#with-index span::after {
content: attr(data-n);
position: relative;
top: -8px;
font-size: 9px;
font-weight: bold;
color: red;
}
#without-index span:nth-child(1n)::after {
content: attr(n);
position: relative;
top: -8px;
font-size: 9px;
font-weight: bold;
color: red;
}
<div id="without-index">
<span>Hello</span> <span>World</span>
</div>
<div id="with-index">
<span data-n="0">Hello</span> <span data-n="1">World</span>
</div>
如果我把索引作为一个属性,我可以使用content: attr(data-n)
。如果有一种方法可以使用 nth-child(1n)
获取 n
的值来达到相同的效果而无需设置任何其他属性?
您可以像这样使用 CSS 计数器:
#without-index { counter-reset: number -1; }
#without-index span::after {
content: counter(number);
counter-increment: number;
position: relative;
top: -8px;
font-size: 9px;
font-weight: bold;
color: red;
}
<div id="without-index">
<span>Hello</span> <span>World</span>
</div>