【问题标题】:Is there a way to access n when using n-th child without javascript?在没有javascript的情况下使用第n个孩子时有没有办法访问n?
【发布时间】:2020-07-14 01:54:30
【问题描述】:

比如说我有:

#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 对它所应用的 HTML 文件一无所知,也不回读数据。所以不,你不能用选择器做任何动态的事情。选项是像使用 data-attr 一样在 HTML 中跟踪它,使用 SCSS/LESS 之类的预处理器(但即使这些也不会告诉你当前的)或使用 JS 解析 DOM。

标签: css css-selectors pseudo-element


【解决方案1】:

您可以像这样使用 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>

【讨论】:

    猜你喜欢
    • 2011-11-04
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2018-06-03
    • 2016-07-04
    • 1970-01-01
    • 2016-01-10
    • 2016-01-19
    相关资源
    最近更新 更多