CSS Counter

CSS counters are variables maintained by CSS that can be used to add automatic numbering to elements. These counters allow for dynamic content generation in HTML without the need for JavaScript. They are especially useful for lists, table rows, or any other type of content that requires numbering.

Key Points on CSS Counter:

Syntax for CSS Counter Properties:

Syntax Example

/* Reset counter */
        counter-reset: counter-name value;
        
        /* Increment counter */
        counter-increment: counter-name value;
        
        /* Display counter */
        content: counter(counter-name);

Examples of CSS Counter Properties:

The following examples demonstrate the usage of different counter properties:

Code Example: Basic Counter Usage

ul {
            counter-reset: item;
        }
        
        li {
            counter-increment: item;
        }
        
        li::before {
            content: counter(item) ". ";
        }

Output

  • First item
  • Second item
  • Third item

Code Example: Nested Counter Usage

ol {
            counter-reset: section;
        }
        
        li {
            counter-increment: section;
        }
        
        li::before {
            content: "Section " counter(section) ": ";
        } 
         

Output

  1. Introduction
  2. Content
  3. Conclusion

Common Counter Properties:

CSS counters offer an efficient way to automate numbering in lists and other HTML structures. They're a lightweight solution for dynamic content generation without resorting to JavaScript.