英文:
How to use CSS counter to prepend the index number before every children?
问题
我有一个如下的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");
}
但它失败了。
英文:
I have a DOM like this:
<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>
How do I use CSS counter to let it rendered as:
1.A
2.B
3.C
4.D
1.Tiger
2.Monkey
3.Fox
I have tried this:
div > div:before {
content: counter ("div > div");
}
But it fails.
Code snippet:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
div>div:before {
content: counter("div > div")
}
;
<!-- language: lang-html -->
<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>
<!-- end snippet -->
答案1
得分: 2
你对counter("div>div")的使用是不正确的。如果给容器添加一个类,那么就不需要div>div。
.container div::before {
counter-increment: section; /* 将section计数器的值递增1 */
content: counter(section) ". "; /* 在每个嵌套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>
英文:
Your use of counter("div>div") was incorrect
If you give the container a class, then you do not need the div>div
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.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;
}
<!-- language: lang-html -->
<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>
<!-- end snippet -->
答案2
得分: 1
.container{
counter-reset: my-counter;
}
div > div::before {
counter-increment: my-counter;
content: counter(my-counter) ". ";
}
英文:
Give container divs a class to reset it between lists and initialize counter in css.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container{
counter-reset: my-counter;
}
div > div::before {
counter-increment: my-counter;
content: counter(my-counter) ". ";
}
<!-- language: lang-html -->
<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>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论