15

我的目标是逐行打印文本文件并在开头附加行号。像这样:

<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 来实现它。

4

1 回答 1

27

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

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

正如 Aaron Lavers 在他的评论中指出的那样,CSS 计数器并不是一个新事物,并且受到 IE8 本身的支持。

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

于 2016-06-15T08:40:41.553 回答