How to add section numbers (1.2, 3.4.1) automatically using CSS?

﹥>﹥吖頭↗ 提交于 2020-06-10 03:49:35

问题


How to add section numbers (1.2, 3.4.1) automatically using CSS?

I currently have

h1, h2, h3, h4 {
  font-weight: normal;
}
h1 { font-size: 140%; }
h2 { font-size: 120%; color:#049;}
h3 { font-size: 110%; color:#06C;}
h4 { font-size: 105%; color:#09C;}

How to modify them so section numbers such as 1.3, 2.4.5 are automatically constructed depending on the nesting level and order of appearance of the section headers?

...

<h2>heading21</h2>
...

<h3>heading31</h3>
...

<h2>heading22</h2>

should show

  1. heading21

    1.1 heading31

  2. heading22

or something along those lines.


回答1:


Hey now you can used CSS counter-increment Property

As like this Css

   body {counter-reset:section;}
    h1 {counter-reset:subsection;}
    h1:before
    {
    counter-increment:section;
    content:"Section " counter(section) ". ";
        font-weight:bold;
    }
    h2:before
    {
    counter-increment:subsection;
    content:counter(section) "." counter(subsection) " ";
    }

HTML **

<p><b>Note:</b> IE8 supports these properties only if a !DOCTYPE is specified.</p>
<h1>HTML tutorials</h1>
<h2>HTML Tutorial</h2>
<h2>XHTML Tutorial</h2>
<h2>CSS Tutorial</h2>
<h1>Scripting tutorials</h1>
<h2>JavaScript</h2>
<h2>VBScript</h2>
<h1>Heading </h1>
<h2>One </h2>
<h2>Two</h2>

**

Live demo http://jsfiddle.net/PfcX2/1/

More info click here https://developer.mozilla.org/en-US/docs/Web/CSS/counter-increment




回答2:


To answer the question if “I only have an h2, how do I suppress the leading 1., alter the h2:before style selector so the h2 must follow the h1 :

h1:before > h2:before {
   // your h2 attributes go here
} 


来源:https://stackoverflow.com/questions/10340276/how-to-add-section-numbers-1-2-3-4-1-automatically-using-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!