What Is the Comma for in CSS Selectors?

Why a Simple Comma Simplifies Coding

You may have wondered what role the comma plays in CSS selector syntax. As in sentences, the comma brings clarity—not code—to the separators. The comma in a CSS selector separates multiple selectors with the same styles.

For example, when you write:

th { color: red; }
td { color: red; }
p.red { color: red; }
div#firstred { color: red; }

You are saying that you want th tags, td tags, paragraph tags with the class red, and the div tag with the ID firstred all to have the style color red.

This is perfectly acceptable CSS.

However, there are two drawbacks to writing it this way:

  • In the future, if you decide to change the font color of these properties to blue, you have to make that change four times in your style sheet.
  • It adds a lot of extra characters to your style sheet that you don’t need.

To can avoid these drawbacks by using commas.

Using Commas to Separate Selectors

Instead, you can combine all these styles into one style property by separating the individual selectors with a comma:

th, td, p.red, div#firstred { color: red; }

Now if you want to change the color from red to blue, you only have to make the change in one location.​ 

Some people choose to make the CSS more legible by separating each selector on its own line:

th,
td,
p.red,
div#firstred
{
  color: red;
}

By using commas between your selectors, you create a more compact style sheet that’s easier to update in the future and that is easier to read.