有没有办法只使用CSS在元素中插入元素的索引(子编号)作为文本?

前端之家收集整理的这篇文章主要介绍了有没有办法只使用CSS在元素中插入元素的索引(子编号)作为文本?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的目标是逐行打印文本文件并在开头添加行号.像这样:
<div id="wrapper">
  <div class="line">1: asdf</div>
  <div class="line">2: asdfasdf</div>
  <div class="line">3: asdfasdfasdfasdf</div>
  <div class="line">4: asdf</div>
</div>

n是CSS中的一个变量,负责其父级内的元素索引,并且在子选择器中可以对其执行操作,例如. nth-child(2n 3)

有没有办法获取此变量并将其作为纯文本插入?基本上是这样的:

.line:before {
  content: n;
}

我知道我可以用SASS完成这个,这就是我正在使用的,我只是想知道是否有一些方法可以用vanilla CSS来实现它.

解决方法

是的,你可以使用CSS计数器来做到这一点.当遇到匹配的选择器时,可以创建CSS计数器并递增.对于这种情况,我们可以在.wrapper元素的级别创建一个计数器,然后在遇到新的.line元素时递增计数器值.

counter-reset属性用于创建计数器,而counter-increment用于递增值.然后可以通过content属性将计数器的值分配给伪元素,其值为counter(counter-name).

正如Aaron Lavers在评论中指出的那样,CSS计数器不是新事物,而且是supported from IE8 itself.

#wrapper {
  counter-reset: line-number;
}
.line {
  counter-increment: line-number;
}
.line:before {
  content: counter(line-number)": ";
}
<div id="wrapper">
  <div class="line">asdf</div>
  <div class="line">asdfasdf</div>
  <div class="line">asdfasdfasdfasdf</div>
  <div class="line">asdf</div>
</div>

我们还可以为输出值设置样式,将值增加1以上的数字,从基值开始,作为不同于0的数字等.

.wrapper {
  counter-reset: line-number 2; /* specifying a number in counter-reset means set the starting value as that number */
}
.line {
  counter-increment: line-number 2; /* specifying a number in counter-increment means increment the counter by that much every time */
}
.line:before {
  content: counter(line-number,lower-roman)": "; /* the second parameter represents the style of the output value */
}

#wrapper2.wrapper .line:before {
  content: counter(line-number,decimal-leading-zero)": ";
}
<h3>Lower Roman Style with Base Value as 2 and increments of 2</h3>
<div id="wrapper" class="wrapper">
  <div class="line">asdf</div>
  <div class="line">asdfasdf</div>
  <div class="line">asdfasdfasdfasdf</div>
  <div class="line">asdf</div>
</div>

<h3>Decimal Leading Zero Style with Base Value as 2 and increments of 2</h3>
<div id="wrapper2" class="wrapper">
  <div class="line">asdf</div>
  <div class="line">asdfasdf</div>
  <div class="line">asdfasdfasdfasdf</div>
  <div class="line">asdf</div>
</div>
原文链接:https://www.f2er.com/css/215780.html

猜你在找的CSS相关文章