使用CSS自动编号嵌套部分

Mic*_*yck 8 html css css-counter

假设我有这样的HTML或XML文档:

<body>
   <section>
      <h1>This should be numbered 1</h1>
      <section>
        <h1>This should be numbered 1.1</h1>
        <p>blah</p>
      </section>
      <section>
        <h1>This should be numbered 1.2</h1>
        <p>blah</p>
      </section>
   </section>
   <section>
      <h1>This should be numbered 2</h1>
      <section>
        <h1>This should be numbered 2.1</h1>
        <p>blah</p>
      </section>
   </section>
</body>
Run Code Online (Sandbox Code Playgroud)

这只是一个说明性的例子; 通常,节中可以有任意数量的子节,并且节可以嵌套到任何深度.

是否可以使用CSS(计数器和生成的内容)在每个节标题的开头生成所需的节号?

我见过这种事情的唯一例子是嵌套列表,但是你可以将'counter-reset'附加到OL并且'counter-increment'附加到LI.在这里,似乎你需要'section'来重置它的子节,并且增加它的父节,并且将它们都附加到一个元素名称不起作用.

dfs*_*fsq 13

在这种情况下,您应该使用CSS计数器.

更新解决方案(更好).最后,一个更灵活的方法是重置body最初的反击,而不是section:first-child任何立即的下一个兄弟h1.

body,
section h1 + * {
    counter-reset: section 0;
}
Run Code Online (Sandbox Code Playgroud)

更新的解决方案.原来我的原始解决方案并不像评论中所指出的那样好.这是修订的正确版本,它应该适用于任意数量的嵌套或兄弟部分.

section:first-child,
section h1 + section {
    counter-reset: section 0;
}
section h1:before {
    counter-increment: section;
    content: counters(section, ".") " ";
}
Run Code Online (Sandbox Code Playgroud)
<section>
    <h1>This should be numbered 1</h1>
    <section>
        <h1>This should be numbered 1.1</h1>
        <p>blah</p>
    </section>
    <section>
        <h1>This should be numbered 1.2</h1>
        <p>blah</p>
    </section>
    <section>
        <h1>This should be numbered 1.3</h1>
        <section>
            <h1>This should be numbered 1.3.1</h1>
            <p>blah</p>
        </section>
        <section>
            <h1>This should be numbered 1.3.2</h1>
            <p>blah</p>
        </section>
    </section>
    <section>
        <h1>This should be numbered 1.4</h1>
        <p>blah</p>
    </section>
</section>
<section>
    <h1>This should be numbered 2</h1>
    <section>
        <h1>This should be numbered 2.1</h1>
        <p>blah</p>
    </section>
    <section>
        <h1>This should be numbered 2.2</h1>
        <p>blah</p>
    </section>
</section>
Run Code Online (Sandbox Code Playgroud)


原(马车).在这种情况下有一些棘手的部分:计数器应该在每个后续增加section.这可以通过section + section选择器实现:

section {
    counter-reset: section;
}
section + section {
    counter-increment: section;
}
section h1:before {
    counter-increment: section;
    content: counters(section, ".") " ";
}
Run Code Online (Sandbox Code Playgroud)
<section>
    <h1>This should be numbered 1</h1>
    <section>
        <h1>This should be numbered 1.1</h1>
        <p>blah</p>
    </section>
    <section>
        <h1>This should be numbered 1.2</h1>
        <p>blah</p>
    </section>
</section>
<section>
    <h1>This should be numbered 2</h1>
    <section>
        <h1>This should be numbered 2.1</h1>
        <p>blah</p>
    </section>
</section>
Run Code Online (Sandbox Code Playgroud)