使用 CSS 到 auto-number 嵌套部分

Using CSS to auto-number nested sections

假设我有这样的 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>

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

是否可以使用 CSS(计数器和生成的内容)在每个 section-title 的开头生成所需的 section-number?

我见过的唯一一个这样的例子是嵌套的 lists,但是你可以将 'counter-reset' 附加到 OL 和 'counter-increment' 给李。在这里,您似乎需要 'section' 来重置其 child-sections,并增加其 parent 部分,并且将这两个附加到一个 element-name 不起作用.

在这种情况下,您应该使用 CSS counters

更新解决方案(更好)。最后,一种更灵活的方法是首先在 body 上而不是在 section:first-child 上以及在 h1.

的任何直接下一个兄弟上重置计数器
body,
section h1 + * {
    counter-reset: section 0;
}

更新解决方案。事实证明,我原来的解决方案并不像评论中指出的那样好。这是修改后的正确版本,它应该可以与任意数量的嵌套或同级部分一起正常工作。

section:first-child,
section h1 + section {
    counter-reset: section 0;
}
section h1:before {
    counter-increment: section;
    content: counters(section, ".") " ";
}
<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>


原始(越野车)。在这种情况下有一个棘手的部分:计数器应该为每个后续 section 递增。这可以通过 section + section 选择器来实现:

section {
    counter-reset: section;
}
section + section {
    counter-increment: section;
}
section h1:before {
    counter-increment: section;
    content: counters(section, ".") " ";
}
<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>

li{
text-align: center;
}


<ol type="1">
  <li>this</li>
  <li>is</li>
  <li>a</li>
  <li>List</li>
</ol>  

那不是 testet 但应该可以