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

Thuộc tính CSS counter-increment

CSS Counters: counter-increment

counter-increment **tăng giá trị** của một counter đã được tạo bởi `counter-reset`. Dùng trong `::before`/`::after` để tự động đánh số.

Cú pháp

counter-increment: <custom-ident> <integer>?;
/* Ví dụ: */
counter-increment: section;       /* Tăng 1 (mặc định) */
counter-increment: section 2;     /* Tăng 2 */
counter-increment: chapter section; /* Tăng cả 2 counter */
counter-increment: none;          /* Không tăng (ghi đè reset) */

Ví dụ hoàn chỉnh (cùng counter-reset)

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      counter-reset: section;           /* Tạo counter "section" = 0 */
    }
    h2::before {
      counter-increment: section;       /* Tăng section lên 1, 2, 3... */
      content: "Fruit " counter(section) " - "; /* Hiển thị */
    }
  </style>
</head>
<body>
  <h1>Fruits</h1>
  <h2>Mango</h2>   <!-- "Fruit 1 - Mango" -->
  <h2>Kiwi</h2>    <!-- "Fruit 2 - Kiwi" -->
</body>
</html>

Quy trình 3 bước bắt buộc

  1. Reset: `counter-reset: name` trên ancestor (thường `body` hoặc container).
  2. Increment: `counter-increment: name` trên element cần đếm.
  3. Display: `content: counter(name)` trong `::before` hoặc `::after`.

Điều khiển số bắt đầu

/* Bắt đầu từ 5 (số đầu hiển thị là 6) */
body { counter-reset: section 5; }

/* Hoặc increment nhảy bước */
h2::before { counter-increment: section 2; } /* 1, 3, 5, 7... */

/* Giảm counter (hiếm dùng) */
h2::before { counter-increment: section -1; }

Nesting: Counter đa cấp (Chapter.Section)

body { counter-reset: chapter; }
h1 { counter-reset: section; }           /* Reset section mỗi chapter */
h1::before {
  counter-increment: chapter;
  content: "Chương " counter(chapter) ": ";
}
h2::before {
  counter-increment: section;
  content: counter(chapter) "." counter(section) " ";
}

Kết hợp với ::marker (List tự động)

ol {
  counter-reset: list-counter;
  list-style: none;
  padding-left: 0;
}
li::before {
  counter-increment: list-counter;
  content: counter(list-counter) ". ";
  font-weight: bold;
  color: #0066cc;
}

Lưu ý

  • Counter **không kế thừa** - con không tự động có counter của cha trừ khi reset lại.
  • Scope: Counter reset tạo scope mới cho subtree đó.
  • Chỉ hoạt động trong `content` của pseudo-element.
  • Screen reader: Cần `aria-label` hoặc text ẩn nếu quan trọng cho accessibility.