CSS Counters

CSS Counters


CSS Counters  
Counters demonstrate the possibility of variable-like values in CSS. 
They are defined as alphanumeric names that correspond to some current counter value in a document. 
In some cases, the counter( ) functional notation is used and in some cases it is not.
Now we will see Example 
Example 1 -
Applying roman numerals styling to the counter output - 
CSS -
body {
counter-reset: item-counter;
}
.item {
counter-increment: item-counter;
}
.item:before {
content: counter(item-counter, upper-roman) ". "; /* by specifying the upper-roman as style the
output would be in roman numbers */

 
HTML - 
<div class='item'>Item No: 1</div>
<div class='item'>Item No: 2</div>
<div class='item'>Item No: 3</div>
Output - 
In the above example, the counter's output would be displayed as I, II, III (roman numbers) instead of the usual 1, 2, 3 as the developer has explicitly specified the counter's style.
Example 2 - 
Number each item using CSS Counter - 
<!DOCTYPE html>
<html lang="en">

<head>
  <style>

body {
counter-reset: item-counter; /* create the counter */
}
.item {
counter-increment: item-counter; /* increment the counter every time an element with class "item"
is encountered */
}
.item-header:before {
content: counter(item-counter) ". "; /* print the value of the counter before the header and
append a "." to it */
}
/* just for demo */
.item {
border: 1px solid;
height: 100px;
margin-bottom: 10px;
}
.item-header {
border-bottom: 1px solid;
height: 40px;
line-height: 40px;
padding: 5px;
}
.item-content {
padding: 8px;
}
  </style>
<div class='item'>
  <div class='item-header'>Item 1 Header</div>
  <div class='item-content'>Lorem Ipsum Dolor Sit Amet....</div>
</div>
<div class='item'>
  <div class='item-header'>Item 2 Header</div>
  <div class='item-content'>Lorem Ipsum Dolor Sit Amet....</div>
</div>
<div class='item'>
  <div class='item-header'>Item 3 Header</div>
  <div class='item-content'>Lorem Ipsum Dolor Sit Amet....</div>
</div>
</head>

<body>
  <div class='item'>Item No: 1</div>
  <div class='item'>Item No: 2</div>
  <div class='item'>Item No: 3</div>
</body>
</html>



 
Output -