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?
<link rel="stylesheet" type="text/css" href="theme.css">
- Константин Ван 2016-02-14 15:58
@import
is a good thing when you have troubles with url()
at CSS. Example: background:url(images/img.jpg)
in css/style.css
will search image at css/images/img.jpg
, while @import
must do it right way - Arman Hayots 2016-03-03 08:28
From a page speed standpoint, @import
from a CSS file should almost never be used, as it can prevent stylesheets from being downloaded concurrently. For instance, if stylesheet A contains the text:
@import url("stylesheetB.css");
then the download of the second stylesheet may not start until the first stylesheet has been downloaded. If, on the other hand, both stylesheets are referenced in <link>
elements in the main HTML page, both can be downloaded at the same time. If both stylesheets are always loaded together, it can also be helpful to simply combine them into a single file.
There are occasionally situations where @import
is appropriate, but they are generally the exception, not the rule.
There are occasionally situations where @import is appropriate
Like using @media
to apply different styles to different devices - XXX 2012-04-05 22:53
@import
for a Google font into the style sheet (e.g. @import url(http://fonts.googleapis.com/css?family=Archivo+Narrow);
), so that you don't have to paste a link
into every page using that stylesheet - cayhorstmann 2013-01-17 05:40
@import
is when you have a build process set up using something like <code>grunt-concat-css</code>. During development, the @import
statements work and page load speed isn't a concern. Then, when you're building for production, a tool like this will concatenate all of your CSS files appropriately and remove the @import
. I do a similar thing with my JavaScript files using <code>grunt-browserify</code> - Brandon 2013-12-03 00:05
''
and whitespace (incl. newlines) with ' '
- Ben Leggiero 2015-04-20 19:42
@import
to apply device specific styles, why not just use a <link>
tag with a media attribute - Jomar Sevillejo 2016-06-10 03:28
@import
would be faster. You're probably looking at some sort of measurement artifact - duskwuff 2017-02-19 18:31
I'm going to play devil's advocate, because I hate it when people agree too much.
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!
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.
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
.
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
@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
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.
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.
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.
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.
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.
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.
I think the key in this are the two reasons why you are actually writing multiple CSS style sheets.
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.
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.
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 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.
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:
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.
<HEAD>
T.Todua 2015-06-17 12:40
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>
file_get_contents()
is considerably slower than using cURL - Connor Simpson 2016-09-16 20:14