如何在CSS中嵌套多个计数器?

Arc*_*ain 3 html css

我想用 CSS 嵌套两个不同的编号,以获得如下所示的自动编号:

1 节1

1-1 小节1

1-2 小节1

2 第2节

2-1 小节2

2-2 小节2

这是我实现这一目标的尝试:

<head>
    <style>
    body
    {
        counter-reset: sectioncount;
    }

    h1:before
    {
        counter-increment: sectioncount 1;
        counter-reset: subsectioncount;
        content: counter(sectioncount) " ";
    }

    h2:before
    {
        counter-increment: subsectioncount 1;
        content: counter(sectioncount) "-" counter(subsectioncount) " ";
    }
    </style>
</head>

<body>    
    <h1>Section1</h1>
    <h2>SubSection 1</h2>
    <h2>SubSection 2</h2>        
    <h1>Section2</h1>
    <h2>SubSection 1</h2>
    <h2>SubSection 2</h2>    
</body>
Run Code Online (Sandbox Code Playgroud)

但分段计数器不会增加。我不明白为什么以及如何解决这个问题。问题是:在 CSS 中实现此目的的正确方法是什么?

myf*_*myf 5

老实说,我不知道确切的原因,但在这种情况下,为主机元素(而不是伪元素)设置计数器可以解决您的问题:

\n

\r\n
\r\n
/**\n  @note 2021-09 this rule is not necessary and\n    \xe2\x9a\xa0 at this moment breaks subsequent resets in Firefox \xe2\x9a\xa0\n  @see https://bugzilla.mozilla.org/show_bug.cgi?id=1729498\n*/\nbody {\n  counter-reset: sectioncount subsectioncount;\n}\n\nh1 {\n  counter-increment: sectioncount 1;\n  counter-reset: subsectioncount;\n}\n\nh1:before {\n  content: counter(sectioncount) " ";\n}\n\nh2 {\n  counter-increment: subsectioncount 1;\n}\n\nh2:before {\n  content: counter(sectioncount) "-" counter(subsectioncount) " ";\n}
Run Code Online (Sandbox Code Playgroud)\r\n
<h1>Section1</h1>\n<h2>SubSection 1</h2>\n<h2>SubSection 2</h2>\n<h1>Section2</h1>\n<h2>SubSection 1</h2>\n<h2>SubSection 2</h2>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n