Daily Tips & Tricks for Web Enthusiasts

Watch Out for Trailing Commas in CSS

When writing code there are a lot of situations where you need to provide a comma-separated list of things. Here’s how you create an array in JavaScript, for example:

var array = [foo, bar, baz];

This array contains foo, bar, and baz.

Some people, for clarity or just preference, will write that same code across several lines, like this:

var array = [
    foo,
    bar,
    baz
];

In JavaScript, the order of the items in an array matters. If you wanted to move baz up to the second position in the array you couldn’t just move that line up, because the commas wouldn’t be in the right places anymore.

In order to avoid this comma problem, and make it both easier and less error-prone to move things around, many people add a trailing comma to the last item, even though there’s nothing that comes after it, like this:

var array = [
    foo,
    bar,
    baz,
];

That makes it easy to move the items in the array around just by moving lines up and down. This is a common practice in many programming languages, and many people have developed a habit of placing a trailing comma after the last item in a comma-separated list like this.

Now, in CSS, you’ll also run into comma-separated lists of things. One of the most common things you’ll see is a list of selectors separated with commas, like this:

h1, h2, h3 {
    color: blue;
}

If you’ve picked up the habit of adding a trailing comma after the last item from another programming language you might be tempted to write something like the following (or you might see this in some CSS someone else wrote):

h1,
h2,
h3,
{
    color: blue;
}

Unfortunately, this CSS won’t work. Adding a comma after the last selector in CSS is not allowed, so adding the comma after the h3 selector will invalidate this selector list.

Furthermore, one of the interesting things about CSS is that any invalid selector in a list of selectors invalidates all of them. Thus, the comma placed after the h3 selector above will prevent the entire ruleset from working, so color: blue; won’t be applied to anything.

So, if you have some CSS that’s not working and you can’t figure out why, make sure you don’t have a trailing comma after the last selector!