DEV Community

Chris DeLuca
Chris DeLuca

Posted on • Originally published at on

Grammatical CSS Lists

The Situation

You have a list of items that you need to render with comma separation, and an “and” at the end.

For example:

Cookies, rice, and farts.

The Problem

This display is traditionally done in business logic, creating more complexity than this simple output warrants.

The Solution

We can use pure CSS, using well supported pseudo-classes and pseudo-content. Behold!


<ul class="list">
  <li class="item">Cookies</li>
  <li class="item">rice</li>
  <li class="item">farts</li>
Enter fullscreen mode Exit fullscreen mode


/* Boilerplate to inline the list. */
.item {
  list-style-type: none;
  display: inline-block;

/* Add a comma after each item. */
.item:after {
  content: ', ';

/* Add the word "and" between the last two items. */
.item:last-of-type:before {
  content: ' and ';

/* Remove the comma after the last item. */
.item:last-of-type:after {
  content: '';
Enter fullscreen mode Exit fullscreen mode


The beauty of this solution is that it’s simple, idiomatic, and declarative, and has the added benefit of taking a hard stand on oxford commas.

I use this solution here on this site for the “Topics” display. If it worked for my little blog, it’ll work for anything else!1

  1. The opinions expressed on my blog are not necessarily endorsed by me. [return]

The post Grammatical CSS Lists first appeared on Chris DeLuca's blog.

Top comments (0)