CSS - 计数器



CSS 计数器充当用于编号目的的变量。它们可以通过 CSS 规则进行增加或减少。计数器使我们能够根据内容的位置修改内容的呈现方式。例如,您可以使用计数器自动为段落、标题和列表分配编号。

body { counter-reset: section; } /* A simple counter when a new h2 element starts */ h2::before { counter-increment: section; content: "Section " counter(section) ": "; }

CSS 计数器是一种由 CSS 维护的变量,可以在文档的不同位置递增、递减或重置。在本教程中,我们将学习如何使用 CSS 实现和管理计数器。

目录

如何在 CSS 中实现计数器?

计数器可用于创建编号列表、章节或任何其他需要计数的内容。请按照以下步骤在网页中创建计数器

  • 初始化计数器: 要开始使用计数器,您首先需要使用counter-reset 属性对其进行初始化。
  • body { counter-reset: section; }

    此示例初始化一个名为 section 的计数器,其初始值为 0。每次 body 元素出现时,计数器都会重置为 0。

  • 递增计数器: 要递增计数器,请使用counter-increment 属性。
  • li::before { counter-increment: section; }

    此示例每次 <li> 元素出现时递增 section 计数器,并在文本前面显示计数。

  • 显示计数器: 要显示计数器的值,请使用counters() 函数。
  • li::before { content: counters(section, ".") " "; }

    此示例在 li 元素的内容前面显示 section 计数器的值,后跟一个句点和一个空格。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

使用计数器进行自动编号

计数器可用于自动对文档中的元素进行编号。以下示例演示了如何使用计数器对列表项进行编号。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> body { counter-reset: section; } h2::before { counter-increment: section; content: "Section " counter(section) ": "; } </style> </head> <body> <h1> CSS Counters</h1> <h2>SQL Tutorial</h2> <h2>JavaScript Tutorial</h2> <h2>Python Tutorial</h2> <h2>HTML Tutorial</h2> <h2>CSS Tutorial</h2> </body> </html>

嵌套计数器

计数器可以嵌套以创建更复杂的编号方案。您可以使用counters() 函数来显示嵌套计数器的值。

示例

Open Compiler
<!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>Section 1 <ol> <li>Subsection 1.1</li> <li>Subsection 1.2</li> <li>Subsection 1.3</li> </ol> </li> <li>Section 2 <ol> <li>Subsection 2.1</li> <li>Subsection 2.2</li> <li>Subsection 2.3</li> </ol> </li> <li>Section 3 <ol> <li>Subsection 3.1</li> <li>Subsection 3.2</li> <li>Subsection 3.3</li> </ol> </li> </ol> </body> </html>

反向计数器

反向计数器是一种特殊的计数器,它向后计数而不是向前计数。要创建反向计数器,在使用 counter-reset 设置它时,使用 reversed() 函数命名它。

body{ counter-reset: reversed(section); }

反向计数器从等于元素数量的默认初始值开始,而不是零。这意味着它可以简单地从元素数量倒数到一。

反向计数器属性仅受 Firefox 浏览器支持

示例

在 Firefox 浏览器中尝试此操作

Open Compiler
<!DOCTYPE html> <html> <head> <style> body { counter-reset: reversed( section); } p::before { counter-increment: section -1; content: "Section " counter(section) ": "; } </style> </head> <body> <p>This is fourth paragraph</p> <p>This is Third paragraph</p> <p>This is second paragraph</p> <p>This is first paragraph</p> </body> </html>

以下是计数器的 CSS 属性列表

属性 描述 示例
counter-reset 用于创建或重置计数器。
counter-set 用于将计数器设置为特定值。
counter-increment 用于递增计数器的值。
counter() 提供一个表示命名计数器当前值的字符串。
counters() 用于处理嵌套计数器。
@counter-styles 用于创建自定义计数器样式。
广告