HTML & CSS
Article
By Adam Roberts

Selector Grouping

By Adam Roberts
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

We can group selectors using a comma (,) separator. The following declaration block will apply to any element that matches either of the selectors in the group:

td, th {
  ⋮ declarations
}

We can think of the comma as a logical OR operator, but it’s important to remember that each selector in a group is autonomous. A common beginner’s mistake is to write groups like this:

#foo td, th {
  ⋮ declarations
}

A beginner might think that the above declaration block will be applied to all td and th elements that are descendants of the element with an ID of “foo”. However, the selector group above is actually equivalent to this:

--ADVERTISEMENT--

#foo td {
  ⋮ declarations
}
th {
  ⋮ declarations
}

To achieve the true goal, write the selector group as follows:

#foo td, #foo th {
  ⋮ declarations
}

Important: No Trailing Comma Needed
Don’t leave a comma after the last selector in the group!

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?