262

Can an ordered list produce results that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with CSS? So far, using list-style-type:decimal has produced only 1, 2, 3, not 1.1, 1.2., 1.3.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Richard77
  • 20,343
  • 46
  • 150
  • 252

13 Answers13

355

You can use counters to do so:

The following style sheet numbers nested list items as "1", "1.1", "1.1.1", etc.

OL { counter-reset: item }
LI { display: block }
LI:before { content: counters(item, ".") " "; counter-increment: item }

Example

ol { counter-reset: item }
li{ display: block }
li:before { content: counters(item, ".") " "; counter-increment: item }
<ol>
  <li>li element
    <ol>
      <li>sub li element</li>
      <li>sub li element</li>
      <li>sub li element</li>
    </ol>
  </li>
  <li>li element</li>
  <li>li element
    <ol>
      <li>sub li element</li>
      <li>sub li element</li>
      <li>sub li element</li>
    </ol>
  </li>
</ol>

See Nested counters and scope for more information.

Alexis
  • 5,681
  • 1
  • 27
  • 44
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 2
    great answer. What is the support for this? – Jason McCreary Nov 05 '10 at 12:03
  • 1
    @Jason McCreary: Well, that’s the down side: [Counters are not supported in IE until version 8](http://www.quirksmode.org/css/contents.html#t21). – Gumbo Nov 05 '10 at 13:45
  • ohhh this is nice... man.. didn't know neither of this possibility. Working in my design now... the only bad thing about this is that the algorithm insert a new DOM object with the number 1.1, 1.2 etc next of the
  • object so some design can be corrupted by this, also you have to set OL{list-style:none}
  • – ncubica Aug 18 '11 at 20:00
  • 3
    This solution misses one tiny thing: the dot following the item number. It doesn't look like the standard list style. Fix by adding a dot to the rule for `li:before`: `content: counters(item, ".")". ";` – Mr. Lance E Sloan Jan 20 '14 at 14:09
  • 4
    This is a poor answer. It doesn't work properly. Check out the answer by Jakub Jirutka below – Mr Pablo Oct 28 '14 at 17:26
  • @MrPablo The question is about numbering and not about fixing indentation. – Gumbo Oct 28 '14 at 18:23
  • 1
    @Gumbo I know, and the answer by Jakub gave me the correct numbering. – Mr Pablo Oct 29 '14 at 10:52
  • This also seems to number un-ordered lists, which is bad – Michael Apr 29 '15 at 22:50
  • @Michael Replace `LI` by `UL > LI`. – Gumbo Apr 30 '15 at 04:12
  • SASS VERSION: ol { counter-reset: item; li { display: block; &:before { content: counters(item, ".") " "; counter-increment: item; } } } – Roy van Wensen Nov 29 '17 at 14:07
  • what if a want the list has a start numer? Like a list starting in 3: 3, 3.1, 3.2, 4, 4.1 ... - – Sebastián Rojas Mar 30 '21 at 22:20
  • Still valid in 2023. Came here because ChatGPT wouldn't give me a solution after many prompt iterations. – Yisus Jul 25 '23 at 16:17