Creating table of contents in html

43,277

Solution 1

This can indeed be done with pure CSS:

ol {
    counter-reset: item;
}

li {
    display: block;
}

li:before {
    content: counters(item, ".")" ";
    counter-increment: item;
}

Same example as a fiddle.

Solution 2

There's quite a number of jQuery plugins to generate a table of contents.

Solution 3

Have you seen this post: Number nested ordered lists in HTML

I don't think it can be done without using JS.

Solution 4

This code leads to the desired output for me:

<ol>
  <li>
    <a href="#Lnk">foo</a>
  </li>
  <li>
    <a href="#Lnk">bar</a>
    <ol>
      <li>
        <a href="#Lnk">baz</a>
      </li>
      <li>
        <a href="#Lnk">qux</a>
      </li>
    </ol>
  </li>
  <li>
    <a href="#Lnk">alpha</a>
    <ol>
      <li>
        <a href="#Lnk">beta</a>
      </li>
      <li>
        <a href="#Lnk">gamma</a>
      </li>
    </ol>
  </li>
</ol>

CSS:

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

Fiddle: http://jsfiddle.net/Lepetere/evm8wyj5/1/

Share:
43,277
Thomas Buckley
Author by

Thomas Buckley

Updated on January 31, 2022

Comments

  • Thomas Buckley
    Thomas Buckley over 2 years

    Is it possible to create an ordered list like the following? I like this for a table of contents I'm creating.

    1. Into
    2. Section1
      2.1 SubSection1
      2.2 SubSection2
    3. Section2
      .....

    I have the following but each subsection restarts from 1.

    <ol>
        <li>
            <a href="#Lnk"></a>
        </li>
        <li>
            <a href="#Lnk"></a>
        </li>
        <ol>
            <li>
                <a href="#Lnk"></a>
            </li>
            <li>
                <a href="#Lnk"></a>
            </li>
        </ol>
    </ol>
    

    Thanks

  • Thomas Buckley
    Thomas Buckley over 11 years
    Thanks wvp. I was hoping it was posisble with js but appears not.
  • jasonkarns
    jasonkarns over 10 years
    Actually, it can be done without JS. See my answer stackoverflow.com/a/21684020/29729
  • cqcn1991
    cqcn1991 about 8 years
  • pheon
    pheon about 5 years
    I couldn't get this to work. Copying the last <ol> tag gave a number 2.3 at the top level instead of the expected 3.
  • jasonkarns
    jasonkarns about 5 years
    @pheon that fiddle has a slight typo. ol can only have li children. Any nested ol must be wrapped within an li. Updated: jsfiddle.net/jasonkarns/6xkzv37e