jasonetco
jasonetco

Reputation: 356

Manually increment a CSS counter

I'd like to be able to reset a CSS counter to 20, starting after the 20th item. The goal is to have two list-items that have an accompanying "20" number, and then to continue the list as normal.

ol {
  list-style-type: none;
  counter-reset: quote-counter;
}
ol .list-item__inner::before {
  content: counter(quote-counter);
  counter-increment: quote-counter;
}

Something like this maybe (this of course does not work)?

li:nth-child(20) {
    counter-reset: quote-counter 20;
}

Upvotes: 2

Views: 872

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159855

Your problem is that the counter-reset property will set the counter before counter-increment gets called so you want to reset to n - 2 to get the repeat you want:

ol {
  list-style-type: none;
  counter-reset: quote-counter;
}
ol li::before {
  content: counter(quote-counter) ". ";
  counter-increment: quote-counter;
}

li:nth-child(6) {
    counter-reset: quote-counter 4;
}
<ol>
  <li>first</li>
  <li>second</li>
  <li>third</li>
  <li>fourth</li>
  <li>fifth</li>
  <li>sixth</li>
  <li>seventh</li>
</ol>

You need n - 2 rather than n - 1 because of the order that counter-reset and counter-increment must be applied. Quoting from the specification:

Inheriting counters must be done before resetting counters, which must be done before setting counters, which must be done before incrementing counters, which must be done before using counters (for example, in the content property).

Since the reset happens before the increment, we need to move the counter back one more place so the increment will put it at the correct number.

Upvotes: 1

Related Questions