CSS计数器输出不匹配

rav*_*n03 5 css

有人可以解释为什么section计数器值在所有h2标签中都打印0 ?

这是源代码:

<!DOCTYPE html>
<html>
<head>
<style>
body {
    counter-reset: section;
    counter-reset: subsection;
}

h1::before {
    counter-increment: section;
    content: "Section " counter(section) ". ";
}

h2::before {
    counter-increment: subsection;
    content: counter(section) "." counter(subsection) " ";
}
</style>
</head>
<body>

<h1>HTML tutorials:</h1>
<h2>HTML Tutorial</h2>
<h2>CSS Tutorial</h2>

<h1>Scripting tutorials:</h1>
<h2>JavaScript</h2>
<h2>VBScript</h2>

<h1>XML tutorials:</h1>
<h2>XML</h2>
<h2>XSL</h2>

<p><b>Note:</b> IE8 supports these properties only if a !DOCTYPE is specified.</p>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

FIL*_*FIL 2

在您的解决方案中,标签中有两个counter-reset属性body

body {
    counter-reset: section;     
    counter-reset: subsection;
}
Run Code Online (Sandbox Code Playgroud)

顾名思义,CSS 是级联的,因此第二次出现的counter-reset属性会覆盖第一次出现的属性。结果counter-reset: section;将被覆盖counter-reset: subsection;并且section重置根本不会被定义。

解决方案

  1. subsection计数器移至标签中h1。然后计数器将为每个标签subsection重置:h1

    body {
        counter-reset: section; 
    }
    
    h1 {
        counter-reset: section; 
    }
    
    Run Code Online (Sandbox Code Playgroud)

body {
    counter-reset: section;     
    counter-reset: subsection;
}
Run Code Online (Sandbox Code Playgroud)

  1. 按照@Temani 建议,定义subsection与计数器内联的计数器。那么计数器不会重置:sectionsubsection

    body {
        counter-reset: section subsection; 
    }
    
    Run Code Online (Sandbox Code Playgroud)

body {
    counter-reset: section; 
}

h1 {
    counter-reset: section; 
}
Run Code Online (Sandbox Code Playgroud)