1. Technology

What is the Comma for in CSS Selectors?


Question: What is the Comma for in CSS Selectors?

The comma in a CSS selector is just a separator that separates multiple selectors that have the same styles.

For example, if you wrote:

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.

But there are two drawbacks to writing it this way:

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

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

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

Some people, to make the CSS more legible, separate each selector on its own line:

  color: red;

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

  1. About.com
  2. Technology
  3. Web Design / HTML
  4. CSS
  5. CSS Selectors
  6. What Is the Comma for in CSS Selectors?

©2014 About.com. All rights reserved.