【问题标题】:SCSS: using @if to include only certain selectors on compilationSCSS:使用@if 在编译时仅包含某些选择器
【发布时间】:2012-03-05 18:55:11
【问题描述】:

我使用三种不同的样式表,它们在网站的不同部分共享大约 70% 的内容。剩下的 30% 各不相同,我目前的做法是维护三个 SCSS 文件(每个一个),使用单独的 @import 语句调用(1)一方面包含共享选择器的部分 SCSS 文件,以及(2)特定的部分带有特定选择器的 SCSS 文件:

/* ===== Primary Styles ==========================================================
   1. Styles used throughout the site <----------- THIS APPEARS IN ALL STYLESHEETS
   =============================================================================== */

@import "partials/page";

/* ===== Specific Styles =====================================================================
   3. Styles specific to this style sheet <-------- THIS SHOULD NOT APPEAR EXCEPT IN STYLE.CSS
   =========================================================================================== */

@import "partials/style-components/page_a.scss";

我这样做的原因是因为三个样式表,一个(样式表 A)——在主页上使用,是迄今为止最短的;第二个(样式表 B),用于站点其余 90 个部分,是平均长度;最后一个(样式表 C),仅用于一页,非常长。一方面减轻主页的负担,并且包含样式表 C 的最后一页所需的非常复杂的选择器是有意义的。

虽然此设置使维护变得可以忍受,但这仍然意味着我必须维护三个独立的设置。我突然想到我可以将主文件减少到一个,在开头设置一个变量,例如$stylesheet-type,可以在编译之前将其更改为type1type2type3,根据需要.

我试图通过将@if 条件应用于所有三个样式表都不通用的选择器来找到实现此目的的方法。困难在于不能在控制指令或 mixin 中使用导入指令。似乎@if 关键字可以决定是否执行包含选择器中的声明时钟的内容。

这肯定会在样式表 B 和 C 中实现一个空的 sidebar-treat 选择器:

$stylesheet-type: "typeA";
// $stylesheet-type: "typeB";
// $stylesheet-type: "typeC";

#sidebar-treat {
    @if $stylesheet-type == typeA {
        margin-border: red; }
    @else {

    }
}

这实际上会更好,SCSS确实编译它:

 $stylesheet-type: "typeA";
 // $stylesheet-type: "typeB";
 // $stylesheet-type: "typeC";

@if $stylesheet-type == typeA {    
    #sidebar-treat {
        margin-border: red;
    }
}

我宁愿不必通过手动将@if 关键字添加到每个选择器的额外步骤(尽管它是一次性的过程),因为这可能容易出错并且涉及一个额外的步骤可能在时间紧迫的情况下经常发生的过程:理想情况下,我希望通过 @import 让不需要的选择器根本不会出现在编译的样式表 B 和 C 中,这可能是有条件的。有什么方法可以实现吗?

【问题讨论】:

    标签: if-statement sass conditional-compilation


    【解决方案1】:

    我通过在编译之前将不需要的内容包装在样式表的不同组件中来解决这个问题,如下所示:

    // $stylesheet-type: "basic";

    $stylesheet-type: "home";
    // $stylesheet-type: "contact";
    // $stylesheet-type: "custom";
    
    // < - - - - ONLY INCLUDED IN STYLE.CSS
    
    @if $stylesheet-type == basic {
    
    
    <!-- Content used only in style.css -->
    }
    
    // [END] < - - - - ONLY INCLUDED IN STYLE.CSS
    
    // < - - - - ONLY INCLUDED IN HOME.CSS
    
    @if $stylesheet-type == home {
    
    
    <!-- Content used only in home.css -->
    
    }
    
    // [END] < - - - - ONLY INCLUDED IN HOME.CSS
    
    < - - - - ONLY INCLUDED IN CONTACT.CSS
    
    @if $stylesheet-type == contact {
    
     <!-- Content used only in contact.css -->
    
    }
    
    // [END] < - - - - ONLY INCLUDED IN CONTACT.CSS
    

    这意味着在将任何布局更改应用到网站时会大大节省时间。

    【讨论】:

      猜你喜欢
      • 2011-05-05
      • 2013-09-21
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2019-05-19
      • 2012-05-26
      相关资源
      最近更新 更多