Skip to content

Instantly share code, notes, and snippets.

@kuroshio
Last active May 15, 2018 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuroshio/1151a701eb516614bcc35c5efaa12970 to your computer and use it in GitHub Desktop.
Save kuroshio/1151a701eb516614bcc35c5efaa12970 to your computer and use it in GitHub Desktop.
Example of hierarchical nested counters using ordered lists with CSS and JavaScript. Supports different color for counter and proper indentation for multi-line bullet content.
<!doctype html>
<html lang="en">
<head>
<title>Nested Counters Example</title>
<style>
ol {
counter-reset: section;
}
ol>li {
display: table;
counter-increment: section;
}
ol>li:before {
color: #76b900;
content: counters(section, ".") ".0";
display: table-cell;
padding-right: 10px
}
ol li ol>li:before {
content: counters(section, ".")
}
</style>
</head>
<body>
<h1>Nested Counters Example</h1>
<p>Example of hierarchical nested counters using ordered lists with JavaScript. Supports different counting styles using standard HTML list-styles. Refer to <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type">MDN list-style-type CSS property</a>.</p>
<ol>
<li>Level 1 list item
<ol>
<li>Level 2 list item</li>
<li>Level 2 list item</li>
</ol>
</li>
<li>Level 1 list item
<ol class="lower-roman">
<li>Level 2 list item</li>
<li>Level 2 list item
<ol class="cjk-ideographic">
<li>Level 3 list item</li>
<li>Level 3 list item</li>
<li>Level 3 list item</li>
</ol>
</li>
<li>Level 2 list item
<ol class="lower-roman">
<li>Level 3 list item</li>
<li>Level 3 list item</li>
<li>Level 3 list item</li>
</ol>
</li>
</ol>
</li>
<li>Level 1 list item
<ol>
<li>Level 2 list item
<ol>
<li>Level 3 list item</li>
<li>Level 3 list item</li>
<li>Level 3 list item
<ol>
<li>Level 4 list item</li>
<li>Level 4 list item</li>
<li>Level 4 list item</li>
</ol>
</li>
</ol>
</li>
<li>Level 2 list item
<ol class="upper-roman">
<li>Level 3 list item</li>
<li>Level 3 list item</li>
<li>Level 3 list item</li>
</ol>
</li>
</ol>
</li>
<li>Level 1 list item
<br>
<span>There is no list for this item</span>
</li>
</ol>
<script>
const createStyle = (styleName) => {
const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = `ol.${styleName} {counter-reset: sec;}
ol.${styleName} > li {counter-increment: sec;}
ol.${styleName} > li:before {content: counters(sec, ".", ${styleName})}`;
document.getElementsByTagName('head')[0].appendChild(style);
}
const olNodes = document.querySelectorAll('ol');
const olStyles = new Set([...olNodes].map(node => node.classList.value));
for (const olStyle of olStyles) {
if (!olStyle) continue;
createStyle(olStyle);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment