Using the CSS Counter Feature

Description

The CSS counter lets you generate numeric content.

The following code uses the CSS Counter Feature.


<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
body {<!-- www.  j  a v  a2s  . c  o  m-->
  counter-reset: myCounter;
}

p:before {
  content: counter(myCounter) ". ";
  counter-increment: myCounter;
}
</style>
</head>
<body>
  <a href="http://java2s.com">Visit the website</a>
  <p>
    I like <span>CSS</span>.
  </p>
  <p>
    I also like <span>HTML</span>.
  </p>
  <a class="myclass1  myclass2" href="http://w3c.org">W3C</a>
</body>
</html>

Click to view the demo

Note

To create a counter, you use the special counter-reset property and set the value to be the name you want to use for the counter, like this:

counter-reset: myCounter;

The code above initializes a counter called myCounter and sets the value to 1.

You can specify a different initial value like this:

counter-reset: myCounter 10;

If you want to define multiple counters, you simply add the names and optional initial values to the same counter-reset declaration, like this:

counter-reset: myCounter 10 othercounter;

The code above creates a counter called myCounter with an initial value of 10 and a counter called othercounter with an initial value of 1.

Then you can use the counter with the :before and :after selectors, like this:


p:before {
  content: counter(myCounter) ". ";
  counter-increment: myCounter;
}

It will include the current value of the counter before every element that the selector matches and append a period and a space after each value.

You can specify other numeric formats as well, like this:

content: counter(myCounter, lower-alpha) ". ";

You may use any of the supported values for the list-style-type property.

You increment the counter using the special counter-increment property. The value for this property is the name of the counter you want to increment, like this:

counter-increment: myCounter;

Counters are incremented by one by default, but you can specify a different increment by adding the step size you want to the declaration, like this:

counter-increment: myCounter 2;




















Home »
  HTML CSS »
    CSS »




CSS Introduction
CSS Background
CSS Border
CSS Box Layout
CSS Text
CSS Font
CSS Form
CSS List
CSS Selectors
CSS Others
CSS Table