在这种情况下,您应该使用
CSS counters.
更新解决方案(更好).最后,一个更灵活的方法是最初重置身体上的计数器而不是部分:第一个孩子以及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,".") " ";
}
This should be numbered 1
This should be numbered 1.1
blah
This should be numbered 1.2
blah
This should be numbered 1.3
This should be numbered 1.3.1
blah
This should be numbered 1.3.2
blah
This should be numbered 1.4
blah
This should be numbered 2
This should be numbered 2.1
blah
This should be numbered 2.2
blah
原创(越野车).在这种情况下有一些棘手的部分:计数器应该为每个后续部分递增.这可以通过截面节选择器来实现:
section {
counter-reset: section;
}
section + section {
counter-increment: section;
}
section h1:before {
counter-increment: section;
content: counters(section,".") " ";
}
This should be numbered 1
This should be numbered 1.1
blah
This should be numbered 1.2
blah
This should be numbered 2
This should be numbered 2.1
blah