CSS 计数器


目录

    显示目录


Pizza

Hamburger

Hotdogs

CSS 计数器是由 CSS 维护的“变量”,其值可以通过 CSS 规则递增(以跟踪它们的使用次数)。计数器可让您根据内容在文档中的位置来调整内容的外观。


使用计数器自动编号

CSS 计数器就像“变量”。变量值可以通过 CSS 规则递增(这将跟踪它们的使用次数)。

为了使用 CSS 计数器,我们将使用以下属性:

counter-reset

- 创建或重置计数器

counter-increment

- 增加计数器值

content

- 插入生成的内容

counter() or counters() function

- 将计数器的值添加到元素

要使用 CSS 计数器,必须首先使用 counter-reset 创建它。

以下示例为页面创建一个计数器(在正文选择器中), 然后增加每个 <h2> 元素的计数器值并添加“计数器的部分:” 到每个 <h2> 元素的开头:

例子

body {
  counter-reset: section;
}
h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}

自己尝试一下 →

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

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

<h1>Using CSS Counters</h1>

<h2>HTML Tutorial</h2>
<h2>CSS Tutorial</h2>
<h2>JavaScript Tutorial</h2>
<h2>Python Tutorial</h2>
<h2>SQL Tutorial</h2>

</body>
</html>




嵌套计数器

以下示例为页面(部分)创建一个计数器,并为每个 <h1> 元素(子部分)创建一个计数器。将使用“Section 节计数器值”对每个 <h1> 元素进行“节”计数器计数,并且将使用“<节计数器的值。子节计数器的值”:

例子

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

自己尝试一下 →

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

h1 {
  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/CSS Tutorials</h1>
<h2>HTML</h2>
<h2>CSS</h2>
<h2>Bootstrap</h2>
<h2>W3.CSS</h2>

<h1>Scripting Tutorials</h1>
<h2>JavaScript</h2>
<h2>jQuery</h2>
<h2>React</h2>

<h1>Programming Tutorials</h1>
<h2>Python</h2>
<h2>Java</h2>
<h2>C++</h2>

</body>
</html>


计数器也可用于制定概述列表,因为新的 计数器的实例会在子元素中自动创建。这里我们使用 counters() 函数在不同级别的嵌套之间插入字符串 柜台:

例子

ol {
  counter-reset: section;
  
list-style-type: none;
}

li::before {
  counter-increment: section;
  
content: counters(section,".") " ";
} 

自己尝试一下 →

<!DOCTYPE html>
<html>
<head>
<style>
ol {
  counter-reset: section;
  list-style-type: none;
}

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

<ol>
  <li>item</li>
  <li>item   
  <ol>
    <li>item</li>
    <li>item</li>
    <li>item
    <ol>
      <li>item</li>
      <li>item</li>
      <li>item</li>
    </ol>
    </li>
    <li>item</li>
  </ol>
  </li>
  <li>item</li>
  <li>item</li>
</ol>

<ol>
  <li>item</li>
  <li>item</li>
</ol>

</body>
</html>



CSS 计数器属性

content

与 ::before 和 ::after 伪元素一起使用,以插入生成的内容

counter-increment

增加一个或多个计数器值

counter-reset

创建或重置一个或多个计数器

counter()

返回指定计数器的当前值