george
george

Reputation: 187

CSS: vertical position of numbering in ordered list

A question regarding the vertical position of numbering in an ordered list: numbers are pushed to the baseline if <li> elements only contain floated divs. Any way to prevent this? I want the numbers aligning at the top.

Here's the fiddle:

ol { 
  margin: 0 2em;
  list-style: decimal outside; 
}

li { 
  margin-bottom: 0.25em;
  border: 1px solid red;
}

li::after {
  content: '';
  display: table;
  clear: both;
}

div { 
  float: left; 
  height: 3em;
  background: lightgrey;
}
<ol>
  <li>
    <div>one two</div>
  </li>
  <li>
    <div>one two three four five</div>
  </li>
</ol>

Thanks!

EDIT: I can't use css counters because the page shall be converted to pdfs which don't support css counters.

Upvotes: 1

Views: 2008

Answers (1)

elveti
elveti

Reputation: 2386

List styling is quite limited in CSS. With list-style-position you can only use inside or outside and you cannot style them. One way to bypass this, is to use CSS counters.

ol { 
  list-style: none; /* removes the current list numbers */
  counter-reset: list; /* creates a new counter */
}

li { 
  position: relative; /* make relative, so we can position the number absolutely */
}

li:before {
  counter-increment: list; /* increment the counter by 1 */
  content: counter(list)'.'; /* output the counter, with a dot at the end */
  position: absolute; /* the rest is positioning and styling */
  right: 100%;
  margin-right: 5px;
  top: 0;
}

Working example: https://jsfiddle.net/zxar91jf/

Upvotes: 4

Related Questions