Buddha Theis Buddha Theis - 5 months ago 20
CSS Question

Specificity rules for comma delineated lists

When using Cascading Style Sheets I have observed the order of specificity as follows:

1st Laws: In-line Styles

2nd Laws: Number of ID Selectors

3rd Laws: Number of Class Selectors

4th Laws: Number of Element Selectors

So, items with in-line styles came first, followed by declarations with one or more ID selectors, followed by declarations with one or more class selectors, followed by declarations with one or more element selectors. With more IDs, classes and elements meaning more precedence, respectively.

From this viewpoint I was unable to comprehend where comma delineated lists of IDs, classes or elements fit. Does a comma delineated list have any special precedence rules? Also, in a single comma delineated list, are IDs, classes and elements considered separate items, for the purposes of calculating specificity?

Code example:

html, body, header {
position: absolute;
top: 0px;
}
header {
position: relative;
top: 50px;
}


What takes precedence in the above example? Is the comma delineated list treated as referencing a single element, in which case the header would take precedence simply for being last in the cascade, or is the comma delineated list treated as multiple elements, and therefore takes precedence? Or are there other rules I should be considering first?

Answer

Remember that CSS is cascading - meaning the style that is referenced FURTHER down a CSS file will take precedence assuming the selector is the same:

header {
  background-color: red;
}
p, span, header {
  background-color: yellow;
}
<header>
  HEADER
</header>

If we switch around the declarations above, the opposite happens:

p, span, header {
  background-color: yellow;
}
header {
  background-color: red;
}
<header>
  HEADER
</header>

As you can see, comma separated selectors / declaration make no difference - they're treated the same as if you'd done them singly.

Comments