Optimize , list items

June 23, 2018

A common solution for adding a , between a list of things in html/css is the following css.

1
2
3
4
5
6
7
li:after {
  content: ', ';
}

li:last-child:after {
  content: '';
}

The first selector adds a comma after each item in a list. The second makes sure the last item isn’t followed by a comma.

A much shorter way of writing this, that should work in most cases, is to append a comma to all but the first item. That would look like this instead.

1
2
3
li:nth-child(n + 2):before {
  content: ', ';
}