How can I increment the counter in my css code?

2.9k views Asked by At

In my html code I have the following list defined:

<p class="list">first.</p>
<p class="list">second.</p>

Now, in css I have:

.list {
  display: table;
}
.list:before {
  display: table-cell;
  counter-increment: counter;
  content: counter(counter) '.';
  padding-right: 5px;
}

and the result on the page is:

1. first
1. second

How can I increment the second number to the value of 2?

5

There are 5 answers

5
kukkuz On BEST ANSWER

You should be using counter-reset property on the wrapper of the lists - see demo below:

body {
 counter-reset:counter;
}
.list {
  display: table;
}
.list:before {
  display: table-cell;
  counter-increment: counter;
  content: counter(counter) '.';
  padding-right: 5px;
}
<p class="list">first.</p>
<p class="list">second.</p>

2
Pawan Developers On

you should use like this:

<ol>
    <li class="list">first.</li>
    <li class="list">second.</li>
</ol>
3
Neelam Khan On

Instead of wrapping your HTML in <p> tags, you could use:

<ol>
  <li>first</li>
  <li>second</li>
</ol>

This will give you the output desired.

Here is a working fiddle.

This way you don't need to do any count stuff in CSS, much easier, simpler solution and compatible cross browser.

0
ssc-hrep3 On

body {
    counter-reset: section;
}

h1 {
    counter-reset: subsection;
}

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

h2::before {
    counter-increment: subsection;
    content: counter(section) "." counter(subsection) " ";
}
<h1>HTML tutorials:</h1>
<h2>HTML Tutorial</h2>
<h2>CSS Tutorial</h2>

<h1>Scripting tutorials:</h1>
<h2>JavaScript</h2>
<h2>VBScript</h2>

<h1>XML tutorials:</h1>
<h2>XML</h2>
<h2>XSL</h2>

Source: http://www.w3schools.com/css/css_counters.asp

5
ab29007 On

You need to reset the counter:

body {
    counter-reset: section;
}
.list {
  display: table;
}
.list:before {
  display: table-cell;
  counter-increment: section;
  content:counter(section) ". ";
  padding-right: 5px;
}
<p class="list">first.</p>
<p class="list">second.</p>