2

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;
}
1
  • Or you could actually decrement the counter by 1 in 20th li element's :after pseudo like here. Commented Mar 30, 2016 at 5:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Worked like a charm, thank you! Would you mind elaborating on why I need to reset to n - 2 though?
counter-reset gets invoked before counter-increment - so to get the same number to repeat, you need to set the counter to desiredNumber - 1 (or in this case nth-child - 2). Changing the last selector to li:nth-child(6)::before should let you use quote-counter: n - 1 (e. g. quote-counter 5).
Actually, belay that point - found the details in the spec - I'll update the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.