Home >Web Front-end >CSS Tutorial >How to Number Nested Ordered Lists Sequentially in HTML?
In HTML, nested ordered lists are typically displayed with nested numbering. By default, each nested level starts from 1 again. However, it may be desirable to number nested elements sequentially.
To achieve sequential numbering, you can utilize the CSS list-style-type and counter-increment properties:
html>/**/body ol { list-style-type: none; counter-reset: level1; } ol li:before { content: counter(level1) ". "; counter-increment: level1; } ol li ol { list-style-type: none; counter-reset: level2; } ol li ol li:before { content: counter(level1) "." counter(level2) " "; counter-increment: level2; }
This method interprets the contents of ol tags as simple lists, allowing for sequential numbering. In the browser, it will display the nested ordered list as follows:
<ol> <li>first</li> <li> second <ol> <li>2.1. second nested first element</li> <li>2.2. second nested second element</li> <li>2.3. second nested third element</li> </ol> </li> <li>third</li> <li>fourth</li> </ol>
For browsers that do not support the CSS approach (IE6/7), you can use jQuery to add the desired numbering:
<script> $(document).ready(function() { if ($('ol:first').css('list-style-type') != 'none') { $('ol ol').each(function(i, ol) { ol = $(ol); var level1 = ol.closest('li').index() + 1; ol.children('li').each(function(i, li) { li = $(li); var level2 = level1 + '.' + (li.index() + 1); li.prepend('<span>' + level2 + '</span>'); }); }); } }); </script>
This JavaScript code targets the unsupported browsers and modifies the unordered list structure to achieve the desired numbering. In these browsers, it will display the nested ordered list as follows:
<ol> <li>first</li> <li> <p>second</p> <p>2.1. second nested first element</p> <p>2.2. second nested second element</p> <p>2.3. second nested third element</p> </li> <li>third</li> <li>fourth</li> </ol>
By combining both approaches, you can ensure that nested ordered lists are numbered sequentially in all major browsers.
The above is the detailed content of How to Number Nested Ordered Lists Sequentially in HTML?. For more information, please follow other related articles on the PHP Chinese website!