Using the CSS @import Rule

Published March 19, 2008 by Rob Glazebrook.

box of crayons

Even the most complex style sheet starts out with a single rule. But when you’re working on a particularly massive and complex website, over time your style sheet will inevitably start to reflect the site’s size and complexity. And even if you employ every trick for organizing your CSS in the book, you might find that the sheer size of the file is simply overwhelming. At that point, you might want to consider splitting your style sheet up into several smaller CSS files. That’s when the @import rule can come in quite handy.

The @import rule is another way of loading a CSS file. You can use it in two ways. The simplest is within the header of your document, like so:

<style>
	@import url('/css/styles.css');
</style>

But that isn’t necessarily the best method for keeping your XHTML small and your code clean. To that end, you can import a style sheet from within another stylesheet. And better still, you can import any number of styles this way. So your document’s head could look like this:

<link rel="stylesheet" type="text/css" href="/css/styles.css" />

Nice and clean. But then your “styles.css” document can contain calls to any number of additional style sheets:

@import url('/css/typography.css');
@import url('/css/layout.css');
@import url('/css/color.css');

/* All three CSS files above will be loaded from
   this single document. */

This lets you break up your gargantuan stylesheet into two or more logical portions — I chose typography, layout and color for this example, but you might prefer dividing your CSS according to the site sections they style (content versus sidebar, etc) or something similar. Either way, the benefit is immense — you can have the same number of CSS rules overall, but in smaller, easier to manage units.

You can even load both your screen and print (or handheld, etc) stylesheets all at the same time using this trick. If you’d like to specify a media, just write your rules like this:

@import url('/css/header.css') screen;
@import url('/css/content.css') screen;
@import url('/css/sidebar.css') screen;
@import url('/css/print.css') print;

Like most cool things in CSS, this one comes with a couple of caveats:

  • The @import rule isn’t recognized by the really old browsers out there… Netscape Navigator 4 skips over @imports entirely, and Internet Explorer 4 ignores them if you don’t use the (entirely optional, but generally used) parentheses. Of course, not too many people these days use either of these archaic browsers. And this problem can actually be useful if you’d like to hide some or all of your CSS from the browsers that can’t really support it.
  • Your @imports must come before all other content in your CSS. And I mean all of your content. Even putting comments before the @import tag will cause your imports to fail. So be sure to do your imports before you do anything else.
  • Internet Explorer (you knew it’d come up eventually) doesn’t deal well with specifying media types – it chokes. Basically, IE (versions 4-7) try to read the media type like it were part of the file name, causing the whole thing to come crashing down. As such, if you don’t want your CSS to have a default media type of “all,” you’re probably better off using a combination of the <link> tag and imports – specifying a media type in your link, and then importing the appropriate CSS within the file you’re linking to. I haven’t yet heard if IE8 suffers from this same problem (if you happen to know, please enlighten me in the comments!).

But even with those caveats in mind, this can be a really useful technique. No matter how big your website ends up getting, you’ll be able to keep your style sheets under control.

50 Responses

  1. Pingback: Matt the web designer » links for 2008-12-20

  2. Sandeep Saroha (reply)

    Exliant Writeup!

    with this technic you can improve your website performance also.
    because you reducing the HTTP request with this technic.

  3. Pingback: Lehetőségek a css kódunk formázására | code&Art

  4. Greg (reply)

    Thanks. I am a CSS newbie and just learned about import and used it on another website. So this helps as I wanted to split menu css from the content css.

  5. Pingback: @import css file - Website Babble Webmaster Forums

  6. Rob (reply)

    I’m fascinated, I’ve seen the same syntax repeated almost everywhere and it doesn’t work for me from inside a .css file or a .html file

    @import ‘navigation.css’; works no brackets no ‘url’ just quotes.

    @import (‘navigation.css’); // with brackets Fails
    @import url(‘navigation.css)’; // with url brackets Fails
    @import url ‘navigation.css’; // with url quotes Fails

    with or without a full http:// path in the bracketed quotes

    I did find the following described as part of an import hack

    quote
    Different versions of the import rule have varying levels of support from older browsers.

    @import “style.css”; /* hidden from nearly all v4 browsers */
    @import url(‘style.css’); /* IE4 can understand, but not NN4 */
    unquote

    I get the same results from IE8 and FF3 the simple syntax – quotes – is the only one that works.

  7. Ben (reply)

    Hi, I thought this would be a great way to include my css reset rules but when I try using a @import for them I get a flash of unstyled (perhaps reset) content for a moment when I load the page before the style kicks in. This didn’t happen before.

    Any ideas?

  8. Ronald (reply)

    Thanks! Nice one.

    @Sandeep Saroha, You’re an idiot! So is your language. If you don’t know anything about the topic, then don’t comment.

  9. Ben (reply)

    @ Ronald, you need to relax.

    Sandeep was actually correct in saying http requests will be reduced by combining stylesheets into one file when using the “@ import” technique. And yes, this will ultimately help reduce page loading times.

  10. Silas (reply)

    Guys after reading the article, i tried my best to go over my code and see if i could find the problem. i just downloaded a free template. it has one layout css and one default css.
    you see on the code below, where id=”logo” it does not display that name. what is wrong with my import tag below?

    Company Name
    Your slogan text here

  11. Samuel Ramírez S (reply)

    It works perfectly, just instead of using:

    Single Quotes = @import url(‘your.css’) screen; inside the brackets

    Use:

    Double Quotes = @import url(“your.css”) screen;

    I know it probably doesn’t make sense but it works for me.

    Good luck you all.

  12. Pingback: 5 Step CSS Weight Loss Program « dU : V 2.0

  13. Ryanqm (reply)

    Sometimes my CSS loads later then the HTML and during css loading the page looks awefull. whats the solution of this problem? is it something with @import?

  14. Katie @ women magazine (reply)

    I have used a theme which has lots of imports at the top of the theme. While going through YSlow logs i tried to copy paste all the import css files to make them as one long css file. Unfortunately, it breaks the UI entirely. Now, i am wondering when these are imported then my site is working fine but when i copy all of them into single css file it breaks the UI, any idea?

  15. ryanqm (reply)

    @Katie, copy the code in your common css in the same order as you had all the @import commands. For example if you had imported a.css and then b.css now you will have to copy the code of a.css above b.css. I hope it will solve your problem

  16. Aeomer (reply)

    1. To prevent the flash of unstyled content add “” to

    2. This technique add additional http requests the first time (1 extra actually for the wrapper) and then the browser should consider the wrapper file a cached entity.

    3. Unfortunately, this technique prevents using ‘auto-versioned’ files where the data type stamp is added to the file name and then stripped by an .htaccess file. If you don’t know what I mean then you need to consider this rewrite rule.

    RewriteCond %{REQUEST_URI} (\.css|\.js|\.bmp|\.jpg|\.jpeg|\.png|\.gif|\.ico|\.swf|\.CSS|\.JS|\.BMP|\.JPG|\.JPEG|\.PNG|\.GIF|\.ICO|\.SWF)$
    RewriteRule ^(.*)\.[\d]+\.(css|js|bmp|jpg|jpeg|png|gif|ico|swf|CSS|JS|BMP|JPG|JPEG|PNG|GIF|ICO|SWF)$ $1.$2

    If you can’t follow that then you need to study. It would take too long to explain here.

  17. Aeomer (reply)

    Looks like this site is stripping script examples!

    Here is the code to stop a flash of unstyled content – remove the extra spaces.

  18. Aeomer (reply)

    I don’t friggin believe this – talk about not knowing how to program a comments system!!!! What is this, Drupal? It strips the script tag rather than escaping it – dumb dumb dumb!

    Here we go again. To stop a flash of unstyled content….

    Change GT to a greater than symbol.
    Change LT to a less than symbol.
    Change FS to a forward slash symbol.
    Change EQ to an equals symbol.
    Change SQ to a single quote.

    LTscript typeEQSQtextFSjavascriptSQGT LTFSscriptGT

  19. Mbinu (reply)

    Guess what ! i think i just sorted the solution to my problems. I have been doing html sites for my clients and some just download the demo site css for free ,using the @ import makes my style-sheets less visible .

    Thanks,
    Great Work

  20. Noah Mccardell (reply)

    How could i extend kids on the Wireless N router? I’ve an Xtreme N handheld router (Dlink). I should extend the reach through the wireless signal. I discover how to undertake it for just a new G signal. I wish to learn how to do them to have an N sign. Is it feasible utilize regular N routers when repeaters. If you do, how can i configure them. Thanks for the information.

  21. Victor (reply)

    change the syntax from:

    @import url(‘/css/typography.css’);
    @import url(‘/css/layout.css’);
    @import url(‘/css/color.css’);

    to

    @import “/css/typography.css”;
    @import “/css/layout.css”;
    @import “css/color.css”;

    Some browsers don’t recognize the simple quotes :P

  22. Gabriel (reply)

    this technique is not recommended !!!
    I am giving you some posts for your attention :

    1)http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

    slide to the section of the @import rule:
    2)http://developer.yahoo.com/performance/rules.html

  23. Pingback: Optimizing webpages for mobile devices, part 2: CSS media queries, Javascript and mobile-specific websites | Frugihoyi's Blog

  24. Pingback: Solution to: Why isn't my css @import statement working? | Xena Beast! All my questions answered!

  25. Amba Junior (reply)

    Thanks Rob for this. Realized it works well without the leading slash, i.e. @import url(‘css/header.css’); not @import url(‘/css/header.css’);

  26. starting slash is absoute path (reply)

    a leading slash would be “absolute unix path” it’s the root
    without it you define a relative path.

    /bla/la.png
    would mean translated to c drive on windows:
    goto c:\bla\la.png

    bla/la.png would mean (if your html/workdir is in c:\work):

    load la.png in subfolder bla within this workdir, absolute translation, load:
    c:\work\bla\la.png
    unix/linux like:
    /work/bla/la.png

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>