WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

CSS Counters


Using CSS Counters

CSS counters resemble "variables". The variable qualities can be augmented by CSS rules (which will track how frequently they are used).

To work with CSS counters we will utilize the accompanying properties:

  • counter-reset - Creates or resets a counter
  • counter-increment - Increments a counter value
  • content - Inserts produced content
  • counter() or counters() work - Adds the estimation of a counter to an element

To utilize a CSS counter, it should initially be made with counter-reset.

The following model makes a counter for the page (in the body selector), at that point increases the counter an incentive for each <h2> component and includes "Section <value of the counter>:" to the start of each <h2> element:

Example

body {
    counter-reset: section;
}

h2::before {
    counter-increase: section;
    content: "Section " counter(section) ": ";
}
Try it yourself »

Nesting Counters

The following precedent makes one counter for the page (segment) and one counter for each <h1> component (subsection). The "section" counter will be meant each <h1> component with "Section <value of the area counter>.", and the "subsection" counter will be tallied for each <h2> component with "<value of the area counter>.<value of the subsection counter>":

Example

body {
    counter-reset: section;
}

h1 {
    counter-reset: subsection;
}

h1::before {
    counter-increase: section;
    content: "Section " counter(section) ". ";
}

h2::before {
    counter-increase: subsection;
    content: counter(section) "." counter(subsection) " ";
}
Try it yourself »

A counter can likewise be helpful to make laid out records on the grounds that another occurrence of a counter is naturally made in tyke components. Here we utilize the counters() capacity to embed a string between various dimensions of settled counters:

Example

ol {
    counter-reset: section;
    list-style-type: none;
}

li::before {
    counter-increase: section;
    content: counters(section,".") " ";
}
Try it yourself »