HTML/CSS multilevel nested lists numbering [duplicate]
Asked Answered
C

2

10

Is there a way to achieve the below numbering using straight HTML and CSS lists (<ul> or <ol>)?

1. Link 1
2. Link 2
3. Link 3
    3.1. Link 3.1
    3.2. Link 3.2
    3.3. Link 3.3
4. Link 4
    4.1. Link 4.1
        4.1.1 Link 4.1.1
        4.1.2 Link 4.1.2
5. Link 5

Thanks in advance!

Canning answered 20/2, 2014 at 13:47 Comment(1)
w3schools.com/cssref/…Washout
A
23

You could use CSS counters:

ol {
    counter-reset: section;
    list-style-type: none;
}

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

Working Demo (also on JSBin):

ol {
  counter-reset: section;
  list-style-type: none;
}

li:before {
  counter-increment: section;
  content: counters(section, ".") ". Link " counters(section, ".") " ";
}
<ol>
  <li></li>
  <li></li>
  <li>
    <ol>
      <li></li>
      <li></li>
      <li></li>
    </ol>
  </li>
  <li>
    <ol>
      <li>    
        <ol>
        <li></li>
        <li></li>
        </ol>
      </li>
    </ol>
  </li>
  <li></li>
</ol>
Arabesque answered 20/2, 2014 at 13:50 Comment(4)
I should note that :before and :after are pseudo-elements, and should use double colons (::before), even though that won't work in IE8.Washout
@Washout CSS Counters is a part of CSS2.1 and works in IE8 as well. But about the pseudo-elements: earlier versions of web browsers (IE8, Opera4-7) used a single colon for both pseudo-elements and pseudo-classes, Hence we're used to use a single color to support the old browsers.Arabesque
There seem to be a problem in such a solution - the numbers become inline with the text following. This does not look good.Mete
@Mete You can create a workaround for that by making ol position relative and li:before position absolute - and positioning it as needed.Hawkshaw
C
0
<style>
OL { counter-reset: item }
LI { display: block }
LI:before { content: counters(item, ".") " "; counter-increment: item }
</style>
<html>
<body>

<ol>
  <li>Link 1</li>
  <li>Link 2</li>
  <li>Link 3
<ol >
  <li>Link 3.1</li>
  <li>Link 3.2</li>
  <li>Link 3.3
<ol >
  <li>Link 3.3.1</li>
  <li>Link 3.3.2</li>
  <li>Link 3.3.3</li>
</ol>
</li>
</ol>
</li>
</ol>

</body>
</html>
Camise answered 20/2, 2014 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.