Counter ng CSS

Pizza

Hamburger

Hotdogs

Ang CSS counter ay isang "variable" na pinapanatili ng CSS, ang halaga nito ay maaaring magdagdag sa pamamagitan ng mga CSS rule (na sinusundan nila sa paggamit).

Ang counter ay nagbibigay sa iyo ng kapangyarihan na ayusin ang anyo nito ayon sa posisyon ng nilalaman sa dokumento.

Automated Numbering na may Counter

Ang CSS counter ay katulad ng "variable". Ang halaga ng variable ay maaaring magdagdag sa pamamagitan ng mga CSS rule (na sinusundan nila sa paggamit).

Upang gamitin ang CSS counter, gagamitin namin ang sumusunod na attribute:

  • counter-reset - gumawa o ireset ang counter
  • counter-increment - magdagdag ng halaga ng counter
  • content - magpakabit ng nilalaman na ginawa
  • counter() o counters() function - magdagdag ng halaga ng counter sa elemento

Upang gamitin ang CSS counter, dapat muna gamitin ang counter-reset Lumikha nito.

Ang sumusunod na halimbawa ay gumawa ng counter para sa pahina (sa selector ng body), at magdagdag ng halaga ng counter sa bawat <h2> elemento, at magdagdag ng "Section <value of the counter>:" sa simula ng bawat <h2> elemento:

Mga halimbawa

body {
  counter-reset: section;
}
h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}

Try It Yourself

Nested Counter

Ang sumusunod na halimbawa ay gumawa ng counter para sa pahina (section), at gumawa ng counter para sa bawat <h1> elemento (subsection).

"section" counter ay nagtatala sa bawat <h1> elemento, at magpapatuloy ng "Section" at ang halaga ng counter ng section, "subsection" counter ay nagtatala sa bawat <h2> elemento, at magpapatuloy ng halaga ng counter ng section at subsection counter:

Mga halimbawa

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) " ";
}

Try It Yourself

Ang counter ay napaka-mahalaga sa paglikha ng mga listahan ng pagkakasurat, dahil ang isang bagong instance ng counter ay gumawa ng awtomatikong counter sa mga anak na elemento. Dito, gamit namin ang counters() Ang function na ito ay nagpapakabit ng string sa pagitan ng counters sa iba't ibang antas ng nested counter:

Mga halimbawa

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

Try It Yourself

CSS Counter Attribute

Attribute Description
content Used with ::before and ::after pseudo-elements to insert generated content.
counter-increment Increment the value of one or more counters.
counter-reset Create or reset one or more counters.