如何使用CSS计数器在每个子节点前添加索引号?

4xy9mtcn  于 2023-02-10  发布在  其他
关注(0)|答案(2)|浏览(147)

我有一个这样的DOM:

<div>
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
</div>

<div>
<div>Tiger</div>
<div>Monkey</div>
<div>Fox</div>
</div>

我如何使用CSS计数器让它呈现为:

1.A
2.B
3.C
4.D

1.Tiger
2.Monkey
3.Fox

我试过这个:

div > div:before {
  content: counter ("div > div");
}

但它失败了。

代码片段:

一个三个三个一个

fivyi3re

fivyi3re1#

计数器("div〉div")的使用不正确
如果为容器提供一个类,则不需要div〉div

.container div::before {
  counter-increment: section; /* Increment the value of section counter by 1 */
  content: counter(section) ". "; /* Display the counter and a dot before the content of each nested div */
}

.container > :first-child {
  counter-reset: section;
}
<div class="container">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
</div>

<div class="container">
  <div>Tiger</div>
  <div>Monkey</div>
  <div>Fox</div>
</div>
4xrmg8kj

4xrmg8kj2#

给container div一个类来在列表和初始化计数器之间重置它。

.container{
   counter-reset: my-counter;
}

div > div::before {
   counter-increment: my-counter;
   content: counter(my-counter) ". ";
}
<div class="container">
    <div>A</div>
    <div>B</div>
    <div>C</div>
    <div>D</div>
</div>
    
    
<div  class="container">
    <div>Tiger</div>
    <div>Monkey</div>
    <div>Fox</div>
</div>

相关问题