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!

MrUpsidown
  • 21,592
  • 15
  • 77
  • 131

2 Answers2

21

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>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
  • 1
    I should note that `:before` and `:after` are pseudo-elements, and should use double colons (`::before`), even though that won't work in IE8. – Bart Feb 20 '14 at 13:52
  • @Bart *CSS Counters* is a part of [CSS2.1](http://www.w3.org/TR/CSS2/generate.html#generate.html#counters) and works in [IE8 as well](http://caniuse.com/#feat=css-counters). 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. – Hashem Qolami Feb 20 '14 at 14:30
  • There seem to be a problem in such a solution - the numbers become inline with the text following. This does not look good. – Ivan Jul 31 '14 at 16:53
  • @Ivan You can create a workaround for that by making ol position relative and li:before position absolute - and positioning it as needed. – Tauri28 Feb 17 '16 at 14:53
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>
Dotnay Tupperson
  • 172
  • 1
  • 10