使用CSS自动编号嵌套部分

时间:2015-07-27 21:30:23

标签: 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>

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

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

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

2 个答案:

答案 0 :(得分:13)

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

更新解决方案(更好)。最后,一个更灵活的方法是重置body上的计数器,而不是section:first-child以及h1的任何直接下一个兄弟。

body,
section h1 + * {
    counter-reset: section 0;
}

更新了解决方案。原来我的原始解决方案并不像评论中所指出的那样好。这是经过修订的正确版本,可以使用任意数量的嵌套或同级部分正常工作。

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

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

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

答案 1 :(得分:-1)

li{
text-align: center;
}


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

那不是测试,但应该工作

相关问题