【问题标题】:CSS numbering using nth-child使用 nth-child 的 CSS 编号
【发布时间】:2016-09-19 06:42:36
【问题描述】:

我有一个div,在div 里面有多个p 标签。我需要使用 css 对它们进行编号。 p 标签的数量可能会有所不同。

使用:nth-child()::before 我可以做这样的事情

div p:first-child::before {
  content: '1 '
}
div p:nth-child(2)::before {
  content: '2 '
}
div p:nth-child(3)::before {
  content: '3 '
}
div p:nth-child(4)::before {
  content: '4 '
}
div p:nth-child(5)::before {
  content: '5 '
}
<div>
  <p>abc</p>
  <p>abc</p>
  <p>abc</p>
  <p>abc</p>
  <p>abc</p>
</div>

如果有大量元素,我该如何实现它。有没有办法在:nth-child()里面的css中设置子编号,像这样。

div p:nth-child(n)::before {
  content: n
}

其中n 是子编号。我知道编号可以使用列表完成,但我需要知道有没有办法在 css 选择器中获取子编号。

【问题讨论】:

    标签: html css css-selectors pseudo-class


    【解决方案1】:

    您可以通过使用::before(IE8 为:before)和counter-reset/increment 来使用CSS counters


    div {
      counter-reset: number;
    }
    p {
      counter-increment: number;
    }
    p::before {
      content: counter(number)" ";
    }
    <div>
      <p>abc</p>
      <p>abc</p>
      <p>abc</p>
      <p>abc</p>
      <p>abc</p>
    </div>

    【讨论】:

      猜你喜欢
      • 2018-07-30
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多