skip to Main Content

How do I make an ordered list work like this, where the numbers are left-aligned (so it doesn’t mess with my layout)?

1. hello
2. x
...
9. x
10. I am left aligned.
...
99. x
100. I am left aligned.

Rather than this (right aligned, the default):

    1. hello
    2. x
    ...
    9. x
   10. I am right aligned.
   ...
   99. x
  100. I am right aligned.

2

Answers


  1. CSS counters might be a good choice, with support goes all the way back to IE 8:

    /* Just to generate all the elements we need */
    
    const ol = document.querySelector('ol');
    
    for (let i = 1; i < 10001; i++) {
      const li = document.createElement('li');
      if (Math.log10(i) % 1) {
        li.textContent = 'x';
      } else {
        li.textContent = 'Left-aligned.'
      }
      ol.appendChild(li);
    }
    ol {
      counter-reset: list;
      list-style: none;
    }
    
    li {
      counter-increment: list;
    }
    
    li::before {
      content: counter(list) '. ';
    }
    
    /* Demo only */
    ol {
      overflow: auto;
      max-height: 300px;
    }
    <ol>
    </ol>
    Login or Signup to reply.
  2. I see a lot of complicated answers where the solution is pretty easy:

    ol {
     list-style-position: inside; /* this is what you need*/
     
     padding: 0;
    }
    <ol>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    </ol>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search