copenndthagen
copenndthagen

Reputation: 50732

How exactly does CSS @import work?

Lets say I have defined a class in my CSS, with the class name repeated in 3 CSS files with diff definitions... In Css1, i define width as 10 px

In Css2, i define width as 20 px

And In Css3,i define width as 30 px

in my HTML file I call/link css1, which has an import for css2 at the top, which again imports css3..

So my question is what width will be applied and how exactly is this decision made?

Upvotes: 3

Views: 1485

Answers (2)

BoltClock
BoltClock

Reputation: 723498

The rule that is ultimately applied is

.myclass { width: 10px; }

because imported stylesheets always come first (in the order in which they're imported of course), then get overridden by whatever comes after in the stylesheet that imports them, so the order of cascade for equally-specific rules is

  1. css3.css
  2. css2.css (overrides the rule in imported css3.css)
  3. css1.css (overrides the rule in imported css2.css)

The "compiled" CSS would look like this so it's clearer how the rules cascade:

.myclass { width: 30px; } /* From imported css3.css */
.myclass { width: 20px; } /* From imported css2.css, overrides css3.css */
.myclass { width: 10px; } /* From css1.css, overrides css2.css */

Upvotes: 8

Quentin
Quentin

Reputation: 943193

Aside from implications around extra HTTP requests and caching, @import is just like putting the contents of the imported file at the point where the @ directive appears in the importing file.

The cascade rules (including specificity and source order) then apply as normal.

Upvotes: 4

Related Questions