Cover Image for CSS Counter
129 views

CSS Counter

In CSS, counters are a powerful feature that allows you to create and manage numbered or labeled counters for different elements on a web page. CSS counters are primarily used with the counter-increment and content properties.

  1. counter-increment: This property is used to increment the value of a named counter. You define the counter with the counter-name of your choice, and every time an element with the specified counter is encountered, its value increases.
  2. content: This property is used to insert generated content before or after an element. It can also be used in conjunction with counters to display the current value of a counter or to add custom text alongside the counter.

Here’s an example of how to use CSS counters:

HTML:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Table of Contents</h1>
  <ol class="toc">
    <li class="toc-item">Introduction</li>
    <li class="toc-item">Getting Started</li>
    <li class="toc-item">Usage</li>
  </ol>
</body>
</html>

CSS (styles.css):

body {
  counter-reset: section-counter;
}

.toc-item {
  counter-increment: section-counter;
}

.toc-item::before {
  content: "Section " counter(section-counter) ": ";
  font-weight: bold;
}

In this example, we have a simple table of contents (<ol> list) with three items (<li> elements). We use the counter-reset property on the body element to reset the section-counter to 0 at the beginning. Then, for each .toc-item, we use counter-increment to increase the value of the section-counter by one for each item.

The ::before pseudo-element is used to insert generated content before each .toc-item. It displays the current value of the section-counter and the custom text “Section ” before the item text.

The final output will be:

Table of Contents
1. Section 1: Introduction
2. Section 2: Getting Started
3. Section 3: Usage

You can use CSS counters in various creative ways to add automatic numbering or labeling to elements on your web page. This is especially useful for creating ordered lists, tables of contents, or any scenario where you need sequential numbering or custom labels for elements.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS