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

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

文件的开头?


当前回答

引自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,因为它会阻止样式表被并发下载。例如,如果样式表A包含以下文本:

@import url("stylesheetB.css");

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

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

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

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

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

这可能会帮助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>

@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

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