[html] Best way to include CSS? Why use @import?

Basically I am wondering what is the advantage / purpose of using @import to import stylesheets into an existing stylesheet versus just adding another ...

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

to the head of the document?

This question is related to html css

The answer is


@Nebo Iznad Mišo Grgur

The following are all correct ways to use @import

@import url("fineprint.css") print;
@import url("bluish.css") projection, tv;
@import 'custom.css';
@import url("chrome://communicator/skin/");
@import "common.css" screen, projection;
@import url('landscape.css') screen and (orientation:landscape);

source: https://developer.mozilla.org/en-US/docs/Web/CSS/@import


Use @import in your CSS if you are using a CSS RESET, like Eric Meyer's Reset CSS v2.0, so it does it's job before applying your CSS, thus preventing conflicts.


There is not really much difference in adding a css stylesheet in the head versus using the import functionality. Using @import is generally used for chaining stylesheets so that one can be easily extended. It could be used to easily swap different color layouts for example in conjunction with some general css definitions. I would say the main advantage / purpose is extensibility.

I agree with xbonez comment as well in that portability and maintainability are added benefits.


I think @import is most useful when writing code for multiple devices. Include a conditional statement to only include the style for the device in question, then only one sheet gets loaded. You can still use the link tag to add any common style elements.


I think the key in this are the two reasons why you are actually writing multiple CSS style sheets.

  1. You write multiple sheets because the different pages of your website require different CSS definitions. Or at least not all of them require all the CSS definitions one other pages require. So you split up the CSS files in order to optimize what sheets are load on the different pages and avoid loading too many CSS definitions.
  2. The second reason that comes to mind is that your CSS is getting that large that is becomes clumsy to handle and in order to make it easier to maintain the large CSS file you split them up into multiple CSS files.

For the first reason the additional <link> tag would apply as this allows you to load different set of CSS files for different pages.

For the second reason the @import statement appears as the most handy because you get multiple CSS files but the files loaded are always the same.

From the perspective of the loading time there is no different. The browser has to check and download the seperated CSS files no matter how they are implemented.


Quoted from http://webdesign.about.com/od/beginningcss/f/css_import_link.htm

The main purpose of @import method is to use multiple style sheets on a page, but only one link in your < head >. For example, a corporation might have a global style sheet for every page on the site, with sub-sections having additional styles that only apply to that sub-section. By linking to the sub-section style sheet and importing the global styles at the top of that style sheet, you don't have to maintain a gigantic style sheet with all the styles for the site and every sub-section. The only requirement is that any @import rules need to come before the rest of your style rules. And remember that inheritance can still be a problem.


I experienced a "high peak" of linked stylesheets you can add. While adding any number of linked Javascript wasn't a problem for my free host provider, after doubling number of external stylesheets I got a crash/slow down. And the right code example is:

@import 'stylesheetB.css';

So, I find it useful for having a good mental map, as Nitram mentioned, while still at hard-coding the design. Godspeed. And I pardon for English grammatical mistakes, if any.


Sometimes you have to use @import as opposed to inline . If you are working on a complex application that has 32 or more css files and you must support IE9 there is no choice. IE9 ignores any css file after the first 31 and this includes and inline css. However, each sheet can import 31 others.


One place where I use @import is when I'm doing two versions of a page, English and French. I'll build out my page in English, using a main.css. When I build out the French version, I'll link to a French stylesheet (main_fr.css). At the top of the French stylesheet, I'll import the main.css, and then redefine specific rules for just the parts I need different in the French version.


There are many GOOD reasons to use @import.

One powerful reason for using @import is to do cross-browser design. Imported sheets, in general, are hidden from many older browsers, which allows you to apply specific formatting for very old browsers like Netscape 4 or older series, Internet Explorer 5.2 for Mac, Opera 6 and older, and IE 3 and 4 for PC.

To do this, in your base.css file you could have the following:

@import 'newerbrowsers.css';

body {
  font-size:13px;
}

In your imported custom sheet (newerbrowsers.css) simply apply the newer cascading style:

html body {
  font-size:1em;
}

Using "em" units is superior to "px" units as it allows both the fonts and design to stretch based on user settings, where as older browsers do better with pixel-based (which are rigid and cannot be changed in browser user settings). The imported sheet would not be seen by most older browsers.

You may so, who cares! Try going to some larger antiquated government or corporate systems and you will still see those older browsers used. But its really just good design, because the browser you love today will also someday be antiquated and outdated as well. And using CSS in a limited way means you now have an even larger and growing group of user-agents that dont work well with you site.

Using @import your cross-browser web site compatibility will now reach 99.9% saturation simply because so many older browser wont read the imported sheets. It guarantees you apply a basic simple font set for their html, but more advanced CSS is used by newer agents. This allows content to be accessible for older agents without compromising rich visual displays needed in newer desktop browsers.

Remember, modern browsers cache HTML structures and CSS extremely well after the first call to a web site. Multiple calls to the server is not the bottleneck it once was.

Megabytes and megabytes of Javascript API's and JSON uploaded to smart devices and poorly designed HTML markup that is not consistent between pages is the main driver of slow rendering today. Youre average Google news page is over 6 megabytes of ECMAScript just to render a tiny bit of text! LOL

A few kilobytes of cached CSS and consistent clean HTML with smaller javascript footprints will render in a user-agent in lightning speed simply because the browser caches both consistent DOM markup and CSS, unless you choose to manipulate and change that via javascript circus tricks.


It is best to NOT use @import to include CSS in a page for speed reasons. See this excellent article to learn why not: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

Also it is often harder to minify and combine css files that are served via the @import tag, because minify scripts cannot "peel out" the @import lines from other css files. When you include them as <link tags you can use existing minify php/dotnet/java modules to do the minification.

So: use <link /> instead of @import.


There is almost no reason to use @import as it loads every single imported CSS file separately and can slow your site down significantly. If you are interested in the optimal way to deal with CSS(when it comes to page speed), this is how you should deal with all your CSS code:

  • Open all your CSS files and copy the code of every single file
  • Paste all the code in between a single STYLE tag in the HTML header of your page
  • Never use CSS @import or separate CSS files to deliver CSS unless you have a large amount of code or there is a specific need to.

More detailed information here: http://www.giftofspeed.com/optimize-css-delivery/

The reason the above works best is because it creates less requests for the browser to deal with and it can immediately start rendering the CSS instead of downloading separate files.


using the link method, the stylesheets are loaded parallel (faster and better), and nearly all browsers support link

import loads any extra css files one-by-one (slower), and could give you Flash Of Unstyled Content


I'm going to play devil's advocate, because I hate it when people agree too much.

1. If you need a stylesheet that depends on another one, use @import. Do the optimization in a separate step.

There are two variables you're optimizing for at any given time - the performance of your code, and the performance of the developer. In many, if not a majority of cases, it's more important to make the developer more efficient, and only then make the code more performant.

If you have one stylesheet that depends on another, the most logical thing to do is to put them in two separate files and use @import. That will make the most logical sense to the next person who looks at the code.

(When would such a dependency happen? It's pretty rare, in my opinion - usually one stylesheet is enough. However, there are some logical places to put things in different CSS files:)

  • Theming: If you have different color schemes or themes for the same page, they may share some, but not all components.
  • Subcomponents: A contrived example - say you have a restaurant page that includes a menu. If the menu is very different from the rest of the page, it'll be easier to maintain if it's in its own file.

Usually stylesheets are independent, so it's reasonable to include them all using <link href>. However, if they are a dependent hierarchy, you should do the thing that makes the most logical sense to do.

Python uses import; C uses include; JavaScript has require. CSS has import; when you need it, use it!

2. Once you get to the point where the site needs to scale, concatenate all the CSS.

Multiple CSS requests of any kind - whether through links or through @imports - are bad practice for high performance web sites. Once you're at the point where optimization matters, all your CSS should be flowing through a minifier. Cssmin combines import statements; as @Brandon points out, grunt has multiple options for doing so as well. (See also this question).

Once you're at the minified stage, <link> is faster, as people have pointed out, so at most link to a few stylesheets and don't @import any if at all possible.

Before the site reaches production scale though, it's more important that the code is organized and logical, than that it goes slightly faster.


They are very similar. Some may argue that @import is more maintainable. However, each @import will cost you a new HTTP request in the same fashion as using the "link" method. So in the context of speed it is no faster. And as "duskwuff" said, it doesn't load simultaneously which is a downfall.


This might help a PHP developer out. The below functions will strip white space, remove comments, and concatenate of all your CSS files. Then insert it into a <style> tag in the head before page load.

The function below will strip comments and minify the passed in css. It is paired in conjunction with the next function.

<?php
function minifyCSS($string)
{
    // Minify CSS and strip comments

    # Strips Comments
    $string = preg_replace('!/\*.*?\*/!s','', $string);
    $string = preg_replace('/\n\s*\n/',"\n", $string);

    # Minifies
    $string = preg_replace('/[\n\r \t]/',' ', $string);
    $string = preg_replace('/ +/',' ', $string);
    $string = preg_replace('/ ?([,:;{}]) ?/','$1',$string);

    # Remove semicolon
    $string = preg_replace('/;}/','}',$string);

    # Return Minified CSS
    return $string;
}
?>

You will call this function in the head of your document.

<?php
function concatenateCSS($cssFiles)
{
    // Load all relevant css files

    # concatenate all relevant css files
    $css = '';
    foreach ($cssFiles as $cssFile)
    {
        $css = $css . file_get_contents("$cssFile.css");
    }

    # minify all css
    $css = minifyCSS($css);
    echo "<style>$css</style>";
}
?>

Include the function concatenateCSS() in your document head. Pass in an array with the names of your stylesheets with its path IE: css/styles.css. You are not required to add the extension .css as it is added automatically in the function above.

<head>
    <title></title>
    <?php
    $stylesheets = array(
        "bootstrap/css/bootstrap.min", 
        "css/owl-carousel.min", 
        "css/style"
        );
    concatenateCSS( $stylesheets );
    ?>
</head>