基本上,我想知道使用@import将样式表导入到现有的样式表中,而不是仅仅添加另一个样式表的优势/目的是什么…
<link rel="stylesheet" type="text/css" href="" />
文件的开头?
基本上,我想知道使用@import将样式表导入到现有的样式表中,而不是仅仅添加另一个样式表的优势/目的是什么…
<link rel="stylesheet" type="text/css" href="" />
文件的开头?
当前回答
从页面速度的角度来看,几乎不应该使用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。
有时你必须使用@import而不是内联。如果你正在开发一个复杂的应用程序,它有32个或更多的css文件,而且你必须支持IE9,那么你别无选择。IE9忽略前31个之后的任何css文件,这包括内联css。但是,每个表可以导入31个其他表。
我认为这里的关键是你为什么要编写多个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文件,无论它们是如何实现的。
引自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.
在头部添加css样式表与使用导入功能并没有太大区别。使用@import通常用于链接样式表,这样可以轻松地扩展样式表。它可以用来轻松地交换不同的颜色布局,例如结合一些一般的css定义。我认为主要的优势/目的是可扩展性。
我也同意xbonez的评论,因为可移植性和可维护性是额外的好处。