csshtml-listslistitem

Increase Space Between Ordered List Numbers and List Item Text


I have an example codepen (https://codepen.io/jon424/pen/YzeBdGK?editors=1100) where I am trying to use custom numbering for ordered lists. The issue occurs when the text for the li wraps to the next line. When this happens (see my list item number 3 in the example), the text is vertically aligned with the ordered list number. I would like to have a margin between the number and the entire content for the wrapping li text so that the ordered list number is not in the same vertical alignment as the li content when it wraps. I would like to try to keep this with only ol and li tags, avoiding a span, and am looking for suggestions.

There is a similar question on SO regarding keeping the indent for the second line of an ordered list , but after researching this approach I am still puzzled with how to keep my list number styles consistent while allowing for the spacing between the numbers and the text. Currently, while trying the table-layout approach, the border radius around the list item is also effected by the display, causing the circles around the numbers to be different sizes depending on the content of the list item.

Any input is greatly appreciated.

HTML

<ol>
  <li>List item</li>
  <li>List item</li>
  <li>Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item</li>
   <li>List item</li>
  <li>List item</li>
</ol>

CSS

ol {
  list-style: none;
  counter-reset: counter-function;
}
li {
  counter-increment: counter-function;
  margin: 0.25rem;
}
li::before {
  content: counter(counter-function);
  background: red;
  width: 2rem;
  height: 2rem;
  border-radius: 50%;
  display: inline-block;
  line-height: 2rem;
  color: white;
  text-align: center;
  margin-right: 0.5rem;
}


Solution

  • Use flexbox on the li

    ol {
      list-style: none;
      counter-reset: counter-function;
    }
    
    li {
      counter-increment: counter-function;
      margin: 0.25rem;
      display: flex;
      align-items: center; /* adjust as needed */
    }
    
    li::before {
      content: counter(counter-function);
      background: red;
      flex: 0 0 2rem;
      height: 2rem;
      border-radius: 50%;
      line-height: 2rem;
      color: white;
      text-align: center;
      margin-right: 1rem; /* adjust as needed */
    }
    <ol>
      <li>List item</li>
      <li>List item</li>
      <li><span>Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item Longer List item</span></li>
      <li>List item</li>
      <li>List item</li>
    </ol>