liveBook · Manning

CSS source order

As explained in CSS in Depth, Second Edition

Source order is the relative position of declarations in stylesheets or included stylesheets, which breaks ties when other cascade criteria are equal.

When two declarations compete for the same property on an element, source order is the cascade’s final tiebreaker. If every earlier criterion is equal, the declaration later in a stylesheet wins. A declaration in a stylesheet included later on the page also wins such a tie. section 1.1.4

A featured navigation link

Suppose ordinary navigation links have a teal background, but a featured link should be orange. The selectors `.nav a` and `a.featured` have equal specificity. Put the orange background declaration second, and it takes precedence for a featured link inside the navigation. section 1.1.4

Listing 1.10 Possible fix number four
.nav a {
  color: white;
  background-color: #13a4a4;
  padding: 5px;
  border-radius: 2px;
  text-decoration: none;
}

a.featured {                #1
  background-color: orange;
}

The listing shows the two competing rules: shared navigation-link styles first, followed by the featured link’s orange background. section 1.1.4

Order cannot overturn a difference that an earlier cascade criterion has already settled. Check selector specificity before moving rules: a lower-specificity `.button` rule cannot override conflicting declarations from `a:any-link` merely by appearing later. section 1.1 section 8.1

Also check where a selector applies. `a.featured` matches featured links outside the navigation, but those links do not receive the styles from `.nav a`. They can end up orange without the navigation link’s other button styling. Choose the selectors and their order with those other uses in mind. section 1.1.4

How CSS in Depth, Second Edition covers it

How deep it goes
Defines the later-declaration rule and works through a navigation-link conflict, stopping short of making source order a substitute for specificity.
Examples
Uses competing navigation-link rules and a featured link outside the navigation to show both the intended result and a styling pitfall.
What it assumes
Assumes familiarity with CSS selectors and stylesheets while unpacking the cascade criteria needed to judge a source-order tie.
What you can do after
Diagnose/debug with it when equal-priority declarations conflict, then check whether a reordered selector also affects links elsewhere.
How it connects
Connects source order to the cascade, selector specificity, stylesheet origin, cascade layers, and scope proximity.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of CSS in Depth, Second Edition. The section links point to the parts of the book it draws on.