0

I would like to go beyond the ideas suggested in e.g. How can you customize the numbers in an ordered list? and use a possibly complicated snippet of HTML to make my own labels in an ordered list. For example:

ol { padding-left: 10em }
li.item-cus-name {
  list-style-type: none
}
span.item-name {
  display: inline-block;
  position: absolute; left: -19.8em;
  width: 30em;
  text-align: right;
}
<ol>
    <li>First item in an ordered list</li>
    <li>Second item</li>
    <li class="item-cus-name"><span class="item-name">Label <em>ehags</em></span>Third</li>
    <li class="item-cus-name"><span class="item-name">c.</span>Fourth</li>
    <li>More</li>
    <li>More</li>
    <li>More</li>
    <li>More</li>
    <li>More</li>
    <li>More</li>
    <li>More</li>
    <li>More</li>
</ol>

What I'm trying to do is to let the <span> element stand in for the usual label, with the label text expanding out to the left (as happens when the usual numbering reaches double digits). This solution is very brittle:

  • If I have an extra long label which overflows the width I've set, it wraps, which I don't want.
  • The exact position required by using absolute positioning needs constant fiddling (e.g. change the padding of the ol element in the example), and doesn't play nicely with, for example, increasing the size of the font.

Surely there is a better way?

Matthew Daws
  • 1,837
  • 1
  • 17
  • 26

1 Answers1

1

If you don't want the text to wrap you can use white-space:nowrap... and positioning the "label" absolutely requires the li to be positioned relative.

If we always tell the label to be 100% right then the spacing between the label and the li is merely a matter of standard margin.

ol {
  padding-left: 10em
}

li {
  position: relative;
}

li.item-cus-name {
  list-style-type: none
}

span.item-name {
  position: absolute;
  right: 100%;
  white-space: nowrap;
  margin-right: .4em; /* adjust to your requirements */
}
<ol>
  <li>First item in an ordered list</li>
  <li>Second item</li>
  <li class="item-cus-name"><span class="item-name">Label <em>ehags.</em></span>Third</li>
  <li class="item-cus-name"><span class="item-name">c.</span>Fourth</li>
  <li>More</li>
  <li>More</li>
  <li>More</li>
  <li>More</li>
  <li>More</li>
  <li>More</li>
  <li>More</li>
  <li>More</li>
</ol>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161