1

I am trying to have a reverse numbered list in html/css that has square brackets around it. Like so:

[3] Item
[2] Item
[1] Item

The solution for the first is easy <ol reversed> and the solution to the second requirement I found on here (HTML numbering with brackets).
However, if I combine these two it doesn't seem to give the intended result.

CSS:

ol.bracket {
counter-reset: list;
}
ol.bracket > li {
list-style: none;
position: relative;
}
ol.bracket > li:before {
counter-increment: list;
content: "[" counter(list) "]  ";
position: absolute;
left: -2em;
}

HTML:

<ol reversed class="bracket">
  <li>First item</li>
  <li>Second item</li>
</ol>

How could I combine the two things?
Thanks for your help! :)

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Peter Schindler
  • 276
  • 1
  • 10
  • 1
    you can increment with a negative number but you need to know the number of element to set the initial value: https://jsfiddle.net/hvmptrf1/ – Temani Afif Sep 22 '19 at 10:40
  • Relevant CSSWG discussion: https://github.com/w3c/csswg-drafts/issues/3686 – BoltClock Sep 22 '19 at 12:54
  • Thanks for the comments! Unfortunately, it's a long list and it would be changing over time - so I don't really want to involve the total number of elements. @temani – Peter Schindler Sep 22 '19 at 20:08

1 Answers1

1

Expanding on the initial comment, here's a CSS+JS solution:

https://jsfiddle.net/hyvyys/Lmay2wft/3/

<ol reversed class="bracket">
  <li>First item</li>
  <li>Second item</li>
</ol>
<ol reversed class="bracket">
  <li>First item</li>
  <li>Second item</li>
  <li>third item</li>
  <li>fourth item</li>
  <li>fifth item</li>
</ol>
document.querySelectorAll('.bracket')
  .forEach(list => {
    const c = list.querySelectorAll('li').length + 1;
    list.style.counterReset = `list ${c}`;
  });
ol.bracket>li {
  list-style: none;
  position: relative;
}

ol.bracket>li:before {
  counter-increment: list -1;
  content: "[" counter(list) "]  ";
  position: absolute;
  left: -2em;
}
Adam Jagosz
  • 1,484
  • 14
  • 13