Is there a way to access n when using n-th child without javascript?

Viewed 46

Say for example I have:

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

If I put the index as an attribute, I can use content: attr(data-n). If there a way using nth-child(1n) to get the value of n to achieve the same effect without having to set any other attribute?

1 Answers

You could use a CSS counter like this:

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

Related