html – 使用CSS自动编号嵌套部分
发布时间:2020-12-31 05:15:46 所属栏目:资源 来源:网络整理
导读:假设我有这样的 HTML或 XML文档: body section h1This should be numbered 1/h1 section h1This should be numbered 1.1/h1 pblah/p /section section h1This should be numbered 1.2/h1 pblah/p /section /section section h1This should be numbered 2/h1
假设我有这样的 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并且’反递增’到LI.在这里,似乎你需要’section’来重置它的子节,并增加它的父节,并将这两个附加到一个元素名称不起作用. 解决方法在这种情况下,您应该使用 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,".") " "; } <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 { 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> (编辑:清远站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |