Following my previous post about progressive enhancement, today I would like to discuss the CSS @import at-rule.
The @import at-rule allows us to link external style rules. Basically, using it we can import rules from other stylesheets. The rule must be the first rule of a stylesheet (apart from the @charset at-rule). The @import rule can contain media queries (comma separated) in order to import specific media rules.
The syntaxAs I said before, the rule have to be placed at the beginning of a stylesheet. Its syntax is:
@import url comma-separated-media-queries;
url = the path of the stylesheet we want to import;
comma-separated-media-queries = the list of media to which the imported rules will be applied (screen, print, mobile etc). If the target browser doesn't support the related media, the rules won't be applied at all.
ExamplesExamples of @import at-rule are:
@import url ('layout.css');
@import url ("layout.css");
@import url ('layout.css') print, mobile;
LinkIf we do not want to use the @import at-rule, we usually link the external stylesheet with the following code, placed in the head of the document:
The above is the same as:
<link href="layout.css" type="text/css">
So, basically the two ways of linking an external stylesheet are the same. Even media queries will work the same way. Using the link, we need to use something like:
While with @import, we use:
<link href="layout.css" type"text/css" media="print">
The two methods are completely interchangeable, as you can see. So which one should we use?
@import url("layout.css") print;
So what?Well, it depends. Considering that the two methods are identical, I believe I can say that it's up to you. The only thing that seems to impact on the user experience, considering the two methods, is how style rules are applied. Infact it seems that rules are loaded following a different pattern with @import, and CSS rules are applied sometimes even after the page is already loaded and displayed.
Many consider the two methods together: a link is used on the page to import a generic stylesheet which contains specific @import at-rules. For those using this solution, it gives them more flexibility in adding new specific stylesheet, without having to revise all the web site pages.
On the compatibility side, we shouldn't worry because all recent browsers understand the @import at-rule (including IE6 and IE7).
What do you use? @import or link? Share your experience, please.