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.
Another one here, with ordered lists
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;
}
Author by
Thomas Buckley
Updated on January 31, 2022Comments
-
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.
- Into
- Section1
2.1 SubSection1
2.2 SubSection2
- 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 over 11 yearsThanks wvp. I was hoping it was posisble with js but appears not.
-
jasonkarns over 10 yearsActually, it can be done without JS. See my answer stackoverflow.com/a/21684020/29729
-
cqcn1991 about 8 yearsAddtional resources: sitepoint.com/5-jquery-table-content-toc-plugins
-
pheon about 5 yearsI 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 about 5 years@pheon that fiddle has a slight typo.
ol
can only haveli
children. Any nestedol
must be wrapped within anli
. Updated: jsfiddle.net/jasonkarns/6xkzv37e