Beware of @import rules when concatenating CSS files

If you like to spread your CSS over multiple files, as many people do (but I don’t), it is generally a good idea to concatenate them before deployment to reduce the number of HTTP requests.

There is one thing to be aware of when doing this—if you use any @import rules they must precede all other rules in that file, as per the CSS 2.1 specification. So if any other than the very first of the CSS files you concatenate has an @import rule, the combined file will violate the specification.

Whether you should be using @import at all is another performance topic which you can read more about in don’t use @import. This article is about what happens when you do use @import, good or not.

Like many others these days you may be thinking “Meh, I don’t care about specs or validation, if it works in browsers it works”. Well, that may be true a lot of the time, but in this case breaking the rules will bite you.

Section 4.1.5 At-rules of the CSS 2.1 specification states the following:

CSS 2.1 user agents must ignore any ‘@import’ rule that occurs inside a block or after any non-ignored statement other than an @charset or an @import rule.

And that’s what user agents do. I made a quick @import test page and found that Chrome, Firefox, IE, Opera, and Safari all ignore invalidly placed @import rules. Depending on what CSS is any @imported file(s), the effect may be immediately obvious or more subtle. Either way it can be tricky to track down what’s causing the problem, especially if you don’t want to use the W3C CSS Validator to check your syntax.

Bottom line: be careful with @import rules and don’t be afraid to let the CSS Validator help you find errors.

Posted on June 14, 2012 in CSS