Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Thuộc tính CSS counter-reset

CSS Counters: counter-reset

counter-reset **tạo mới hoặc reset** một bộ đếm (counter) CSS. Dùng kết hợp với counter-increment và content: counter() để tự động đánh số thứ tự (heading, list, figure, table...).

Cú pháp

counter-reset: <custom-ident> <integer>?;
/* Ví dụ: */
counter-reset: section;           /* Tạo counter "section", bắt đầu từ 0 */
counter-reset: section 3;         /* Bắt đầu từ 3 (số tiếp theo là 4) */
counter-reset: chapter 0 section; /* Reset nhiều counter cùng lúc */

Ví dụ: Tự động đánh số Heading

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      counter-reset: section;           /* 1. Khởi tạo counter "section" = 0 */
    }
    h2::before {
      counter-increment: section;       /* 2. Tăng counter trước khi dùng */
      content: "Fruit " counter(section) " - "; /* 3. Hiển thị giá trị */
    }
  </style>
</head>
<body>
  <h1>Fruits</h1>
  <h2>Mango</h2>   <!-- Hiển thị: "Fruit 1 - Mango" -->
  <h2>Kiwi</h2>    <!-- Hiển thị: "Fruit 2 - Kiwi" -->
</body>
</html>

Cơ chế hoạt động

  1. counter-reset trên ancestor (thường là `body` hoặc container) tạo counter = 0.
  2. counter-increment trên element cần đếm tăng giá trị lên 1 (mặc định).
  3. content: counter(name) trong `::before`/`::after` hiển thị số.

Nesting Counters (Đa cấp)

body {
  counter-reset: chapter;
}
h1::before {
  counter-increment: chapter;
  content: "Chapter " counter(chapter) ". ";
  counter-reset: section;  /* Reset section ở mỗi chapter mới */
}
h2::before {
  counter-increment: section;
  content: counter(chapter) "." counter(section) " ";
}

Hiển thị kiểu số khác nhau

counter(name)           /* Decimal: 1, 2, 3... */
counter(name, lower-roman)    /* i, ii, iii... */
counter(name, upper-roman)    /* I, II, III... */
counter(name, lower-alpha)    /* a, b, c... */
counter(name, upper-alpha)    /* A, B, C... */
counter(name, lower-greek)    /* α, β, γ... */
counter(name, cjk-decimal)    /* 一, 二, 三... */
counter(name, disc)           /* ● ● ● (bullet) */

Ứng dụng thực tế

  • Tự động số thứ tự: Figure 1, Figure 2... Table 1, Table 2...
  • Breadcrumbs, pagination, legal documents, technical specs.
  • Không cần JavaScript - thuần CSS, accessible cho screen reader.

Lưu ý

Counter hoạt động trên **pseudo-elements** (`::before`, `::after`). Không thể dùng trực tiếp trong `content` của element thường.