MulaiCode
CSS

CSS Counters

Pelajari cara membuat penomoran otomatis di HTML menggunakan CSS Counters.

CSS Counters

CSS Counters digunakan untuk membuat daftar atau elemen dengan penomoran otomatis hanya menggunakan CSS, tanpa perlu JavaScript.


Contoh Dasar CSS Counter

<style>
  body {
    counter-reset: section; /* Membuat counter baru */
  }
 
  h2::before {
    counter-increment: section; /* Menambahkan counter */
    content: "Section " counter(section) ": ";
  }
</style>
 
<h2>Introduction</h2>
<h2>HTML</h2>
<h2>CSS</h2>
<h2>JavaScript</h2>

Penjelasan

  • counter-reset: section; — Menginisialisasi counter dengan nama section.
  • counter-increment: section; — Menambah nilai counter setiap kali elemen h2 muncul.
  • content: "Section " counter(section) ": "; — Menyisipkan nilai counter sebelum teks.

Contoh Daftar Bersarang

<style>
  ol {
    counter-reset: item;
  }
 
  li {
    counter-increment: item;
  }
 
  li::before {
    content: counters(item, ".") " ";
  }
 
  li ol {
    counter-reset: item;
  }
</style>
 
<ol>
  <li>HTML
    <ol>
      <li>Elements</li>
      <li>Attributes</li>
    </ol>
  </li>
  <li>CSS
    <ol>
      <li>Selectors</li>
      <li>Properties</li>
    </ol>
  </li>
</ol>

CSS Counters sangat berguna untuk:

  • Nomor urut bab dalam dokumen.
  • Membuat daftar isi otomatis.
  • Penomoran nested list yang rapi.

On this page