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">
  <li>Azure</li>
  <li>CSS</li>
  <li>C#</li>
</ul>
(8th Jan 2018)

By default that will look like this:

image

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:

image

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:

image

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:

image

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.

Comments

Comment by ClinicalPosters

Thanks for the tip. I modified the code to style tags on my site:

.styled-tags {

display: inline;

list-style: none;

line-height: 2.3;

background: #f4f6fc;

border: none;

border-radius: 0.5em;

padding: 3px 6px 4px 6px;

margin-top: 10px;

margin-right: 3px;

margin-bottom: 10px;

li:last-child::after {

content: "";

}

}

ClinicalPosters
Comment by Steven Meyer

Hi, is it possible to do the opposite? taking a coma separated list and convert it to an unordered list?

Steven Meyer
Comment by Nicole Köhler

Hi thank you! I found out that you can do it in one line of css code.
.comma-list li:not(:last-child)::after {
content: ", ";
}

Nicole Köhler
Comment by Mark Heath

awesome!

Mark Heath