0 Comments Posted in:

I recently blogged about how to style striped lists in CSS. This time, I want to look at how to style a comma separated list. This was another feature I needed for my blog rewrite in order to show the list of categories each post was in.

Suppose I have the following HTML containing list of categories:

Posted in:
<ul class="comma-list">
(8th Jan 2018)

By default that will look like this:


We want to get this all onto one line with commas between the categories. So first of all we'll reset the default styling by turning off the list-style and setting the padding to 0. We'll also set display: inline so that it gets rendered on the same line as "Posted in:".

.comma-list {
  display: inline;
  list-style: none;
  padding: 0px;

We'll also need to set the list items to display: inline to get everything onto a single line

.comma-list li {
  display: inline;

Now it looks like this:


We're getting close now, but of course there are no commas between items. We can insert them by using the CSS ::after selector to place a comma (and a space) after every list item:

.comma-list li::after {
  content: ", ";

This gives us almost what we need, but now we have a trailing comma after the last category:


We can get rid of the trailing comma by combining the ::after selector with the :last-child selector:

.comma-list li:last-child::after {
    content: "";

And we get the desired effect:


Again, I'm sure this is all very basic for CSS experts, but it was new to me. You can play with a full example on CodePen.

Vote on HN