The "counter-increment" property in CSS

The counter-increment CSS property is used to increment one or more CSS counters. 

CSS counters are variables maintained by CSS whose values can be incremented or decremented.

We can use incremented counters to generate content using the content property or display their values using the counter() or counters() function. 

This property is especially useful for automatically numbering items in lists or sections of content.


Example to demonstrate the use of "counter-increment" CSS property

    

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Counter Increment Example</title>
<style>
/* Define a counter named 'list-counter' */
body {
    counter-reset: list-counter;
}

/* Increment the 'list-counter' for each <li> element */
li {
    counter-increment: list-counter;
}

/* Style the counter with a period after the number */
li::before {
    content: counter(list-counter) ".";
    margin-right: 0.5em;
    font-weight: bold;
}
</style>
</head>
<body>

<!-- Example list with automatic numbering -->
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

</body>
</html>

    

In the above example:

We first define a counter named 'list-counter' using counter-reset. This initializes the counter to a value of 0.

We then apply the counter-increment property to the <li> elements within the <ul> list. This increments the 'list-counter' for each list item.

Finally, we use the content property with the ::before pseudo-element to insert the value of the 'list-counter' before each list item. We format it as "1.", "2.", etc., by referencing the counter using the counter() function.

When you open this HTML file in a browser, you'll see a numbered list:

1. Item 1
2. Item 2
3. Item 3

Although, we can see that the list items are wrapped in unordered list tag (<ul>), still we see the list items as numbered list when rendered. That is each list item is automatically numbered based on its position in the list, this is thanks to the counter-increment property.

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

The Basic Structure of a Full-Stack Web App

Unlocking Web Design: A Guide to Mastering CSS Layout Modes