/*! Ads Here */

List number CSS

Colored list numbers

What about numbered lists? The idea is the same: we have to replace the automatic counter that we cannot style by one that we generate ourselves. Apart from the properties above, we also need to create a counter. Say we use a counter called 'li'. We first set it to zero on the OL element:

ol {list-style: none; counter-reset: li}

And then we use it like we did the bullet above:

li::before {content: counter(li); color: red; display: inline-block; width: 1em; margin-left: -1em}

One more thing is missing: As it is our own counter, we're responsible for augmenting it as well:

li {counter-increment: li}

The result looks like this:

That may be enough, but if you have more than nine items, it looks like this:

  1. First item
  2. Second item
  3. Third item
  4. Fourth item
  5. Fifth item
  6. Sixth item
  7. Seventh item
  8. Eighth item
  9. Ninth item
  10. Tenth item

while you'd probably prefer this:

  1. First item
  2. Second item
  3. Third item
  4. Fourth item
  5. Fifth item
  6. Sixth item
  7. Seventh item
  8. Eighth item
  9. Ninth item
  10. Tenth item

That requires four changes: moving the numbers a bit further to the left and adding that extra amount as margin on the right, right-aligning the list numbers, and setting the direction of the text to 'rtl'. Why the 'rtl'? I'll explain below.

.example ol li::before {content: counter(li); color: red; display: inline-block; width: 1em; margin-left: -1.5em; margin-right: 0.5em; text-align: right; direction: rtl}

We put the numbers in a box that is 1em wide and align them to the right. But if the numbers are wider than the box, they will not be right aligned, but left aligned. Text is not allowed to overflow a box on the left side in CSS unless it is text in a right-to-left language, such as a Hebrew or Arabic. The numbers aren't Hebrew or Arabic letters and so they don't actually go right to left, but by saying our box follows the rules for right-to-left text, we allow the numbers to overflow on the left and thus remain correctly aligned on the right.

(If you dont want to add the direction: rtl, you can omit it and instead use a larger width and left margin, e.g., width: 2em; margin-left: -2.5em. That should provide enough space for correctly aligning numbers up to 999.)

Video liên quan

*

Đăng nhận xét (0)
Mới hơn Cũ hơn

Responsive Ad

/*! Ads Here */

Billboard Ad

/*! Ads Here */