CSS: managing import rules

The at-rule @import is used by CSS to import the content of a style sheet into another. This kind of rule must appear at the beginning of your CSS file, like so:

@import "external.css";

/* Other style rules */

The first problem that you may encounter with imported CSS is due to cascade: if you have subsequent conflicting rules in your main CSS file, then these rules will win over those used in your imported one because of the fact that both style sheets are parsed as a unique CSS file, so the rules of your main file will come later in source.

Another problem that you may encounter is merging imported style sheets with a server-side language. For example, in a past project I used the following approach:

@import "base.css";
@import "layout.css";
@import "typography.css";
@import "colors.css";

The server-side developer (who used Ruby) encountered several problems when trying to merge these files properly and in the correct order, due to some issues with his Ruby version. Anyway, be aware of this fact.

The most relevant problem with this approach is, above all, performance. If you take the above example, a browser must execute five GET requests, one for the main file and four for the imported style sheets. If your site is a small blog or a content-centric web site, then you won't probably notice the difference. On the contrary, if you're working on a complex web application or on a huge Web 2.0 web site, then you'll probably see noticeable delays in the rendering of your web pages.

I'm not saying that you should not use these rules. Far from it. I'm only saying that, like for other CSS features, you should always take the pros and cons into account before writing your code.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.