Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered list in HTML that is numbered using odd numbers

Using <ol type="1"> in HTML, I can get an ordered list to look like this:

  1. I like cheese
  2. Cookies are nice
  3. Cream is good ...

How would I use <ol> to get an ordered list to only have odd numberings, like this?

1.I like cheese

3.Food is nice

5.I wish upon a star...

like image 751
Joshua Lin Avatar asked Jan 06 '23 01:01

Joshua Lin


1 Answers

I don't think this can be achieved with normal ordered lists because the only attributes available seem to be the following (even including HTML5):

  • type (indicates the numbering type)
  • start (indicates the starting value)
  • reversed (indicates whether the list is in reversed order)

But it can be achieved using CSS counters like in the below snippet. CSS counters is not a new thing and has very good browser support.


Implementing this with counters is pretty simple and only needs the following steps:

  • Create (reset) a counter using the counter-reset property at the parent. The counter-reset property generally takes the name of the counter and the starting value as parameters. Here, I have used -1 as the starting value because at every li the increment should be by 2 and the start value needs to be 1 (so -1+2 = 1).
  • Increment the counter's value by 2 every time a li is encountered. This makes the counter to have only odd numbered values. Again the counter-increment property also generally takes 2 parameters - one is counter name and the other is the value by which it should be incremented.
  • Display the counter's value before the list item using the :before pseudo-element and content property.

ol {
  counter-reset: odd-numbers -1;
  list-style-type: none;
}
li {
  counter-increment: odd-numbers 2;
}
li:before {
  content: counter(odd-numbers) ". ";
}
<ol>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ol>

Another option without setting -1 as the start value would be to use the li:first-child selector and increment the counter only by 1 (default value and so it needn't be specified in counter-increment). For the rest of the li we can increment it by 2.

ol {
  counter-reset: odd-numbers;
  list-style-type: none;
}
li:first-child {
  counter-increment: odd-numbers;
}
li {
  counter-increment: odd-numbers 2;
}
li:before {
  content: counter(odd-numbers) ". ";
}
<ol>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ol>
like image 139
Harry Avatar answered Jan 07 '23 15:01

Harry