CSS counter

The CSS counter is set by a variable, and the variable is incremented according to the rule.
The following properties are used in CSS counters:

  1. counter-reset-Create or reset a counter
  2. counter-increment-increment variable
  3. content-insert the generated content
  4. counter() or counters() function-add the value of the counter to the element

Instance

The example code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS 计数器</title>
<style>
body {
  counter-reset: section;
}

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

<h1>使用 CSS 计数器:</h1>
<h2>HTML 教程</h2>
<h2>CSS 教程</h2>
<h2>JavaScript 教程</h2>

<p><b>注意:</b> IE8 需要指定 !DOCTYPE 才可以支持该属性。</p>

</body>
</html>

Instance running results:
Instance run results

Nested counter

The nested counter code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>嵌套计数器</title>
<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 教程:</h1>
<h2>HTML 教程</h2>
<h2>CSS 教程</h2>

<h1>Scripting 教程:</h1>
<h2>JavaScript</h2>
<h2>VBScript</h2>

<h1>XML 教程:</h1>
<h2>XML</h2>
<h2>XSL</h2>

<p><b>注意:</b> IE8 需要指定 !DOCTYPE 才可以支持该属性。</p>

</body>
</html>

The effect of nested counter operation is as follows:
Nested counter

CSS counter applied to the list

Counters can also be used in lists, and the child elements of the list are automatically created. Here we use the counters() function to insert strings in different nesting levels:

CSS example:

ol {
  counter-reset: section;
  list-style-type: none;
}
 
li::before {
  counter-increment: section;
  content: counters(section,".") " ";
}

The overall code of the list counter is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<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>

<p><b>注意:</b> IE8 需要指定 !DOCTYPE 才可以支持该属性。</p>

</body>
</html>

The results are as follows:
List counter

Guess you like

Origin blog.csdn.net/Serena_tz/article/details/114061073