基本上,我想知道使用@import将样式表导入到现有的样式表中,而不是仅仅添加另一个样式表的优势/目的是什么…

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

文件的开头?


在头部添加css样式表与使用导入功能并没有太大区别。使用@import通常用于链接样式表,这样可以轻松地扩展样式表。它可以用来轻松地交换不同的颜色布局,例如结合一些一般的css定义。我认为主要的优势/目的是可扩展性。

我也同意xbonez的评论,因为可移植性和可维护性是额外的好处。


我认为这里的关键是你为什么要编写多个CSS样式表的两个原因。

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. 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.

第一个原因是附加的<link>标记将应用,因为这允许您为不同的页面加载不同的CSS文件集。

对于第二个原因,@import语句似乎是最方便的,因为您可以获得多个CSS文件,但加载的文件总是相同的。

从装载时间的角度来看并没有什么不同。浏览器必须检查和下载分离的CSS文件,无论它们是如何实现的。


从页面速度的角度来看,几乎不应该使用CSS文件中的@import,因为它会阻止样式表被并发下载。例如,如果样式表A包含以下文本:

@import url("stylesheetB.css");

然后,第二个样式表的下载可能要等到第一个样式表下载完成后才开始。另一方面,如果在主HTML页面的<link>元素中引用了这两个样式表,则可以同时下载这两个样式表。如果两个样式表总是一起加载,那么将它们合并到一个文件中也会很有帮助。

有时@import是合适的,但它们通常是例外,而不是规则。


出于速度考虑,最好不要使用@import在页面中包含CSS。看看这篇优秀的文章,了解为什么不去:http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

此外,通过@import标记来缩小和合并css文件通常更困难,因为缩小脚本不能从其他css文件中“剥离”@import行。当你将它们包含为<link标签时,你可以使用现有的minify php/dotnet/java模块来进行缩小。

所以:使用<link />代替@import。


使用link方法,样式表可以并行加载(更快更好),而且几乎所有浏览器都支持link

import加载任何额外的css文件一个接一个(较慢),并可以给你Flash的无风格的内容


它们非常相似。有些人可能认为@import更易于维护。但是,每个@import都将花费您一个新的HTTP请求,其方式与使用“link”方法相同。所以在速度的背景下,它并不更快。正如“duskwuff”所说,它不能同时加载,这是一个缺点。


我经历了一个可以添加链接样式表的“高峰”。虽然添加任何数量的链接Javascript对我的免费主机提供商来说都不是问题,但在外部样式表数量翻倍后,我就崩溃/变慢了。 正确的代码示例是:

@import 'stylesheetB.css';

所以,就像Nitram提到的那样,我发现在硬编码设计时,拥有一个好的心理地图是很有用的。 祝成功。 如果有语法错误的话,我原谅你。


我使用@import的一个地方是当我处理一个页面的两个版本时,英语和法语。我将使用main.css用英文构建我的页面。在构建法语版本时,我将链接到一个法语样式表(main_fr.css)。在法语样式表的顶部,我将导入main.css,然后为法语版本中需要不同的部分重新定义特定的规则。


@Nebo在伊兹纳德米索格古尔

下面是使用@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);

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


如果你使用的是CSS RESET,比如Eric Meyer的RESET CSS v2.0,在你的CSS中使用@import,这样它就能在应用你的CSS之前完成它的工作,从而防止冲突。


(2022年更新:我应该指出的是,许多专业开发人员现在使用SASS这样的系统来管理他们的CSS,或者与React兼容的框架,其中任何一种都可以在内部处理这些优化。)

我要唱反调了,因为我讨厌人们意见太一致。

1. 如果您需要一个依赖于另一个样式表的样式表,请使用@import。在单独的步骤中进行优化。

任何时候都有两个变量需要优化——代码的性能和开发人员的性能。在许多情况下,如果不是大多数情况下,更重要的是使开发人员更有效率,只有这样才能使代码更性能。

如果有一个样式表依赖于另一个样式表,最合乎逻辑的做法是将它们放在两个单独的文件中,并使用@import。这对于下一个查看代码的人来说是最有逻辑意义的。

(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.

样式表通常是独立的,所以使用<link href>来包含它们是合理的。但是,如果它们是一个依赖的层次结构,那么您应该做最合乎逻辑的事情。

Python使用import;C用法包括;JavaScript有require。CSS有import功能;当你需要它的时候,使用它!

2. 一旦你达到了站点需要扩展的程度,连接所有的CSS。

任何类型的多个CSS请求——无论是通过链接还是通过@imports——对于高性能网站来说都是糟糕的做法。一旦你到了优化很重要的时候,你所有的CSS都应该通过一个minifier来流动。Cssmin组合import语句;正如@Brandon指出的那样,grunt也有多种选择。(另见此问题)。

一旦到了简化阶段,<link>更快,正如人们指出的那样,所以最多链接到一些样式表,尽可能不要@import任何样式表。

然而,在网站达到生产规模之前,代码的组织性和逻辑性比稍微快一点更重要。


引自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.


我认为@import在为多种设备编写代码时最有用。包含一个条件语句来只包含有问题的设备的样式,然后只加载一个表。您仍然可以使用link标记来添加任何公共样式元素。


几乎没有理由使用@import,因为它会分别加载每个导入的CSS文件,并会显著降低网站的速度。如果你对处理CSS的最佳方式感兴趣(当涉及到页面速度时),以下是你应该如何处理所有CSS代码:

打开所有CSS文件,复制每个文件的代码 将所有代码粘贴到页面HTML头中的单个STYLE标记之间 永远不要使用CSS @import或单独的CSS文件来交付CSS,除非你有大量的代码或有特定的需要。

更多详细信息请访问:http://www.giftofspeed.com/optimize-css-delivery/

上面的效果最好的原因是因为它为浏览器创建了更少的请求,它可以立即开始呈现CSS,而不是下载单独的文件。


有时你必须使用@import而不是内联。如果你正在开发一个复杂的应用程序,它有32个或更多的css文件,而且你必须支持IE9,那么你别无选择。IE9忽略前31个之后的任何css文件,这包括内联css。但是,每个表可以导入31个其他表。


这可能会帮助PHP开发人员。下面的函数将删除空白,删除注释,并连接所有CSS文件。然后在页面加载前将其插入到头部的<style>标签中。

下面的函数将剥离注释并缩小在css中的传递。它与下一个函数一起配对。

<?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;
}
?>

您将在文档的头部调用此函数。

<?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>";
}
?>

在文档头中包含concatenateCSS()函数。传入一个数组,其中包含样式表的名称及其路径IE: css/styles.css。您不需要添加扩展名.css,因为它是在上面的函数中自动添加的。

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

是的,在你的网站上总是使用@import和外部级联样式表!

更新:8/22/2022

(在过去的10年里,网上有很多关于@import的错误信息,我打算纠正。所以请仔细阅读下面我的信息。)

第一条规则

Never Rely on JavaScript API's or Tricks to Manage Cascading Style Sheets!! Do NOT rely on 3rd party vendor CSS solutions! Never use SASS, React, Modernizr, Bootstrap, or Angular to manage CSS. I know, I have used them all. Always manage Cascading Style Sheets yourself using hand-written CSS text files and your site will not only run faster, but you will have total control over your websites design and your user experience. If you rely on these poorly designed systems they will fail in numerous scenarios, slow down your site, and fail in numerous versions of older browsers...too many to count.

规则二

是的,总是使用@import!它作为使用CSS的现代解决方案非常棒。我强烈推荐!它已经在数百个浏览器中使用了20多年,没有任何问题。许多年轻的、缺乏经验的开发人员对@import有错误的假设,包括在典型的页面请求期间@import会“阻止”网页脚本、HTML或其他资产的下载。这些都是完全错误的。我将在下面证明它!

规则三

Use of @import in your CSS does NOT slow down page load or parsing. Multiple @imports combined in an embedded <style> element all download in parallel to each other. (That is true even for very old IE browsers). In the case of multiple @import rules called from inside a <link> external style sheet, these also all download in parallel and use the same connection as the parent style sheet that holds them. They just do not download in parallel to the parent sheet and any CSS it might include. More on that later.

规则四

CSS does NOT need to be compressed, minimized, preprocessed, etc. And CSS download size, or multiple external CSS files using @import is NOT a problem on the Web. Most style sheets are rarely over 30 kilobytes in size. Compare this to the 1-5 Megabytes in a typical JavaScript API library, which is a bandwidth hog, and you will see why CSS downloads do not delay or slow down browser content. Make sure you realize that fact. These tiny imported sheets of style text is a fragment of the much larger download footprint of a typical web page download, which explodes in size when using these modern JavaScript libraries, emoticons, images, videos, and media files shoved into the block stream of a typical user's browser during a modern web page display request. That is why you also should never compress your CSS or preprocess it using SASS as the savings in download time or parsing and render-tree display are almost zero.

阻塞CSS不是问题,@import也不是bug或过时的技术。它是一种非常可靠的老式编码解决方案,已经运行了20多年。

但你可能仍然想知道@import如何才能真正帮助我?

Let's look at an example. Most developers import external style sheets to divide up sections of styles they either want to manage in modules or to hide from certain browsers. In this linked sheet below, all imported sheets are added to a single parent style sheet to manage them in one location. When the linked sheet is parsed during HTML download by the browser, a connection is open (or reused) and all these imported sheets download in parallel to each other over the connection. So, we would add the parent sheet to hold our imported external CSS sheets as follows:

<link media="screen" rel="stylesheet" type="text/css" href="parent.css" />

...then inside the parent.css sheet above we have the following @import children. They all should download in parallel and in most browsers and share the same TCP connection. Most modern web browsers have 6 or more, so that means CSS will never block HTML or other page downloads and parsing. Plus, many servers in 2022 now support HTTP2 that includes Multiplexing which means all these tiny CSS file downloads can now share a single connection with other requests. These small text files download FAST in modern browser using @import!

@import url('child1.css');
@import url('child2.css');
@import url('child3.css');
@import url('child4.css');

In the second example below, these @import declarations embedded in an HTML <style> tag should also all download in parallel to each other, just randomly. Again, this worked this way in many older browsers, as well as newer ones. From what I have read, they might have order issues using @import like this, but your CSS should rarely be dependent on cascade order in this type of design. By the way, there are numerous formats for writing @import. Use the format @import url('mycss.css'); when writing this type of media query to improve the chances your modern HTML5 browser will parse your import file CSS code reliably:

<style>
  @import url('child1.css');
  @import url('child2.css');
  @import url('child3.css');
  @import url('child4.css');
</style>

@import只有在以下有限的情况下才会出现问题:

You are using IE version 4-9, primarily, which had historically limited connections (IE6 had only 2 connection to the server, for example). With these browsers various @import and linked CSS in combination fail to download in parallel. This would affect <link> CSS downloads, too, so this isn't a real case against @import. In the first case above where a <link> parent style sheet holds imported sheets, because the parent sheet has to connect and parse its CSS file first, it adds one extra connection to the server. That makes logical sense and should be expected. If your sheet only has imports and no CSS, which I recommend, with no CSs to parse @import begins immediately and should use the same connection to download the file as the parent. In the first case above where a <link> parent style sheet holds multiple imported sheets, IF the parent sheet also has additional CSS after the @imports declarations, then yes there would be a true "blocking" CSS connection. In that one case the parent CSS file has to be downloaded first, complete its CSS parsing and download first, discover the @imports, THEN download the @import styles and place them before the CSS in the file before the file is complete. This makes logical sense and why you should NEVER combine CSS with @import style rules in any CSS style sheet. I never do that. If you remove the CSS in the parent file, imports immediately call down their files over the parent files connection without delay. If you combine a <link> style sheet that has no imported rules with either a linked style sheet with an @import or an embedded <style> with @import, in Internet Explorer ONLY, they generally wont download in parallel. The other browsers manage this fine. As mentioned this may be related to IE's limited browser connections.

因此,基于这些规则,在大多数情况下,@import工作正常。主要的问题是当将@import添加到有大量纯CSS的工作表中时。这种类型的事情是有意义的,但会导致很长时间的延迟,因为父节点解析自己的CSS,然后发现额外的@imports。

请记住,现代浏览器大约有6个可用的连接,所以@import不会成为瓶颈,有太多的文件或太多的大文件加上非异步JavaScript会阻碍你的网页解析和渲染。顺便说一下,你现在下载的JavaScript API是1.5兆字节!

使用@import管理旧浏览器版本的CSS显示

使用@import也有很多好的理由!

使用@import的一个重要原因是进行跨浏览器设计。通常,导入的工作表对许多旧的浏览器都是隐藏的,这允许您为非常旧的浏览器应用特定的格式,如Netscape 4或更老的系列,用于Mac的Internet Explorer 5.2,用于PC的Opera 6和更老版本,以及用于PC的IE 3和4 ....然后使用@import添加一个这些浏览器无法看到的现代样式表,因为许多旧的浏览器无法识别某些版本的@import。

例如,添加一个普通的样式表,所有的浏览器都可以看到,无论是旧的还是新的:

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

...用这个CSS里面…

body {
  font-size:13px;
}

现在,在您导入的自定义表(newerbrowser .css)中,只需应用较新的样式来重写上面的样式,仅用于较新的浏览器。较新的浏览器使用“em”单位,较旧的使用“px”单位。下面这个版本的@import在很多旧浏览器中都看不到,包括IE 1-7、MAC IE 5、Netscape 4和许多其他浏览器:

<link media="screen" rel="stylesheet" type="text/css" href="newerbrowsers.css" />

...只有较新的浏览器才能看到@import。使用这个@import格式和'all',它将在IE1-7浏览器中隐藏,以及更多!

@import 'imported.css' all;

...在@import…

html body {
  font-size:1em;
}

使用“em”单位优于“px”单位,因为它允许字体和设计根据用户设置进行拉伸,而旧的浏览器则更好地使用基于像素的单位(这是刚性的,不能在浏览器用户设置中更改)。大多数旧浏览器都无法看到导入的表。

我在上面发布的@import表规则现在从下面列出的所有旧浏览器中隐藏了,现在你可以单独设置样式或完全忽略它们,让你的团队现在可以为现代HTML5浏览器设计!

- Netscape 1-4.8 
- Opera 1-3.5
- Windows Internet Explorer 1-7.x
- Macintosh Internet Explorer 2-4.5
- Konqueror 1-2.1
- Windows Amaya 1-5.1
- iCab 1-2
- OmniWeb
- Many more antiquated browsers...

您可能会说,“谁会关心旧的浏览器呢!”试着去一些更大的老式政府或公司网络,那里有成千上万的旧Windows PC或Mac电脑,你仍然会看到那些旧的浏览器在使用!但这真的只是好的设计,因为你今天喜欢的浏览器有一天也会过时。在有限的范围内使用CSS意味着你现在有一个更大且不断增长的用户代理群体,他们不能很好地与你的网站合作。

Using @import, your cross-browser web site compatibility will now reach 99.99% positive web browser display saturation simply because so many browsers understand imported sheets. You can also manage CSS linked CSS for the older browsers and use imported CSS to manage all your newer browser styles and layouts using my solution above. It guarantees you apply basic CSS for older agents, but more advanced CSS3+ is delivered to newer ones. This allows content to be accessible for older browsers without compromising rich visual displays needed in newer desktop browsers or having to manage hundreds of complex CSS hacks and fixes for various browser versions.

Remember also that modern browsers cache HTML structures and CSS extremely well after the first call to a web site. That's the whole purpose in using linked and imported external CSS. One call, one cache! Besides, multiple calls to the server is not the bottleneck it once was, anyway. 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. For example, do a viewsource on many Google website pages and download all the megabytes and megabytes of sync'ed and async'ed JavaScript that comes with it! Your average Google news page is well over 6 megabytes of ECMAScript just to render a tiny bit of text! Bad!!

几千字节的缓存CSS和一致的干净HTML以及较小的Javascript占用将以闪电般的速度呈现在用户代理中,这仅仅是因为浏览器一次缓存外部文件、标记和CSS。不要使用巨大的Javascript杂技技巧来操纵和改变网站的自然解析流程。依靠您自己创建的小CSS文件,使用@import下载它们,您的站点每次都会完美显示。

顺便说一下,你可以在这里下载这个样式表系统:通用CSS框架


现代浏览器可以使用css文件定义全局变量。该文件可以导入到其他可以使用该变量的css文件中。

例如,要在站点中使用一致的颜色:

colors.css :根{ ——bg-dark: # ffffff; } home.css @ import“colors.css”; 身体:var(——bg-dark)