Why last format doesn't override earlier format?

Viewed 42

I have the following formats:

td:nth-child(6) { /* Saturday */
    color: #ff7f7f;
}

td:nth-child(7) { /* Sunday */
    color: #ff0000;
}

and later

.prevmonth, .nextmonth {
    color: gray;
}

where prevmonth and nextmonth are classes in <td>-tags.

But the days from last month or next month are not shown in gray when they are a Saturday or Sunday.

Why the later format does not override the earlier format?

I helped myself by extending the earlier format with ...:not(.prevmonth, .nextmonth). That works fine.

1 Answers

CSS not only uses the latest selector for styling, it also uses the rule of specificity. If your selector is more specific (targeting an id, for example), it will override less specific selectors.
When the selectors have the same specificity, then the last one "wins".

This is used when working with CSS frameworks quite often. They give you a default style for a selector and you can copy the selector and override that style in a file which is added after the frameworks' files.

But of course it makes sense that styling an ID should have preference, since you give only exactly that one HTML element the ID, so the styling must be exclusive to that element as well.
You might have default stylings for table, but it makes sense table.sortable for example is a more specific styling for a table. It inherits the table styling and applies more or different styles when the table has class sortable as well.

All browsers implement CSS specificity.

Links:

So the answer.. or more of a task:

In your example, classes are more specific than pseudo-elements.
You will have to change selectors so they override themselves according to specificity. This takes a little time to set up, but at least you don't spam !important everywhere.

To quote the MDN:

Selector Types

The following list of selector types increases by specificity:

  • Type selectors (e.g., h1) and pseudo-elements (e.g., ::before).
  • Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover).
  • ID selectors (e.g., #example).
  • Universal selector (*), combinators (+, >, ~, ' ', ||) and negation pseudo-class (:not()) have no effect on specificity. (The selectors declared inside :not() do, however.)

For more information, visit: "Specificity" in "Cascade and inheritance", you can also visit: https://specifishity.com

Inline styles added to an element (e.g., style="font-weight: bold;") always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity.

Related