Ol element alignment with CSS
After years of working with CSS I discovered yet another limitation with the default list-style-type when set to outside. The alignment appears to be thrown off once you hit the double digits so I decided to investigate a solution using ordered list attributes and pseudo elements to properly position the numbers to the left.
Here is an example of a regular ordered list:
- First list item
- Second list item
When going into double digits the numbers do not adjust itself to the left hand side…
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
- Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
To fix this we can use any custom attribute and build this into a style declaration which allow us to properly align the numbers to the left hand side:
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
- Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
HTML code sample:
<ol class="ol-align" start="9">
<li n="9">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
<li n="10">Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</li>
</ol>
CSS code sample:
.ol-align {
padding-left: 28px;
}
.ol-align li {
position: relative;
list-style-type: none;
}
.ol-align li:before {
content: attr(n)".";
position: absolute;
left: -28px;
}