CSS - counter-reset 属性



要使用 CSS 计数器属性,第一步涉及通过 counter-reset 属性创建它。 这将启动重置计数器的过程。使用 counter-reset 属性时,默认情况下,counter 初始化为零。

可能的值

  • <custom-ident> - 计数器的名称。名称可以是任何字符串值。
  • <integer> − (可选) 每次元素出现时计数器重置为的默认值。 此值可以为零,甚至可以为负数。如果未提供整数,则计数器将重置为零。
  • none - 不会重置计数器。

语法


counter-reset: <counter name> <integer> | reversed( <counter-name> ) <integer> ;

适用于

所有 HTML 元素。

CSS 计数器重置 - <custom-ident> 值

下面是一个反复位的示例:


<html>
<head>
<style>
	 	body {
	 	 	 counter-reset: heading;
	 	} 	 	
	 	h1::before {
	 	 	 counter-increment: heading;
	 	 	 content: "Heading " counter(heading) ": ";
	 	}
</style>
</head>
<body>
	 	<h1>Introduction</h1>
	 	<p>This is the introduction section.</p> 	
	 	<h1>Background</h1>
	 	<p>This is the background section.</p>
	 	<h1>Conclusion</h1>
	 	<p>This is the conclusion section.</p>
</body>
</html>

CSS 计数器重置 - <integer>值

该程序演示了具有整数值的 counter-reset 属性的用法。 在此示例中,我们将 body 元素的 counter-reset 属性设置为 head-counter 5,这会将 head-counter 计数器的值重置为 5。


<html>
<head>
<style>
	 	body {
	 	 	 counter-reset: head-counter 5;
	 	}
	 	h1::before {
	 	 	 counter-increment: head-counter;
	 	 	 content: counter(head-counter) " -";
	 	}
	 	h2::before {
	 	 	 counter-increment: head-counter;
	 	 	 content: counter(head-counter) " -";
	 	}
	 	h3::before {
	 	 	 counter-increment: head-counter;
	 	 	 content: counter(head-counter) " -";
	 	}
</style>
</head>
<body>
	 	<h1>Heading 1</h1>
	 	<h2>Heading 2</h2>
	 	<h3>Heading 3</h3>
	 	<h3>Heading 3</h3>
	 	<h2>Heading 2</h2>
	 	<h1>Heading 1</h1>
</body>
</html>

CSS counter-reset - 反转计数器

counter-reset 属性的值反转。它用于反转计数器。

截至目前,这仅适用于Firefox浏览器。

h1 {
	 	counter-reset: reversed(item) ;
	 	 	 /* Sets the reversed flag on the item counters.
	 	 	 	 	Sets the items to the number of elements */
	 	 }
	 	 p {
	 	 	 counter-reset : reversed(unit) ;
	 	 	 /* Sets the reversed flag on the unit counters.
	 	 	 Sets the units to the number of elements */
	 	 }

以下示例演示了此功能(在Firefox浏览器中执行此示例):


<html>
<head>
<style>
	 	body {
	 	 	 counter-reset: reversed(chapter);
	 	}
	 	h1::before {
	 	 	 counter-increment: chapter -1;
	 	 	 content: "Chapter " counter(chapter) ": ";
	 	}
</style>
</head>
<body> 		
		 	<h1>Introduction</h1>
		 	<p>This is the introduction of the book.</p>
		 	<h1>Unit One</h1>
		 	<p>This is the first unit of the book.</p>
		 	<h1>Unit Two</h1>
		 	<p>This is the second unit of the book.</p>
	 	 <h1>Unit Three</h1>
		 	<p>This is the third unit of the book.</p>
</body>
</html>