【问题标题】:Iterate over theme-variable files in SCSS迭代 SCSS 中的主题变量文件
【发布时间】:2017-01-23 19:44:29
【问题描述】:

我想使用主题设置文件为 WordPress 主题创建不同的 css 主题。设置(简化)如下:

/themes/_theme1.scss
/themes/_theme2.scss
/components/_file1.scss
/components/_file2.scss
/theme.scss

这个想法是通过在文档正文中添加一个类来实现简单的主题化,例如.theme-theme1.theme-theme2。在_theme#.scss 文件中,我想定义文本颜色、字体大小等变量。在_file#.scss 中定义了实际样式。

我现在的问题是,如何在填充 files.scss 的同时迭代主题设置文件。

示例创意,背景颜色:

body {

###foreach themefile###
&.theme# {
    background-color: $background-color;
}
###/foreach###

}

我知道如何在生成的 CSS 文件中只使用一个主题来执行此操作,但我想在生成的 CSS 中使所有主题都可用。请随意询问更多细节,因为我不确定我是否解释正确。

有没有办法通过某种 foreach 循环通过主题文件中的变量创建此样式表,还是必须为每个主题文件使用额外的 scss-rules 来完成?

【问题讨论】:

    标签: sass compass-sass compass


    【解决方案1】:

    有点可能使用@import@mixin 的组合来生成样式。这种方法应该产生最少的重复代码。

    以下是我们将如何设置文件。

    - scss
      - themes
        - _theme1.scss
        - _theme2.scss
      - _theme.scss
      - styles.scss
    

    一些文件上的_ 前缀阻止它们被编译成CSS,以保持我们的构建整洁。现在让我们来看看文件的内容:

    _theme1.scss

    $theme-name: 'theme1';
    
    $primary-color: red;
    $primary-font-size: 24px; 
    

    _theme2.scss

    $theme-name: 'theme2';
    
    $primary-color: blue;
    $primary-font-size: 12px;
    

    这是一个过于简单的例子,但应该给出基本的想法。每个主题文件将只包含变量。

    _theme.scss

    @mixin themestyle() {
      body.#{$theme-name} {
        p {
          color: $primary-color;
          font-size: $primary-font-size;
        }
    
        .bordered {
          border: 3px solid $primary-color;
        }
      }
    }
    

    themestyle mixin 将包含每个主题的所有样式,使用来自/themes/_theme*.scss 文件的变量。 body.#{$theme-name} 将根据$theme-name 变量的当前值创建像body.theme1body.theme2 这样的选择器。

    在这个演示中,我在 p 标记上设置样式,但这可以很容易地扩展到您网站的所有元素/选择器。要记住的重要一点是所有样式都需要在 body.#{$theme-name} 选择器内。

    现在是最后的,最少的 DRY 部分。 styles.scss 文件将导入每个主题文件,然后调用 themestyle mixin 为每个主题生成样式。

    styles.scss

    @import 'themes/theme';
    
    /* Theme 1 Styles */
    @import 'themes/theme1';
    @include themestyles();
    
    /* Theme 2 Styles */
    @import 'themes/theme2';
    @include themestyles();
    

    重复的@import/@include 是必需的,因为不可能在循环或mixin 中@import,或者这可以进一步优化。

    一旦styles.scss 被编译,输出将是:

    /* Theme 1 Styles */
    body.theme1 p {
      color: red;
      font-size: 24px; }
    body.theme1 .bordered {
      border: 3px solid red; }
    
    /* Theme 2 Styles */
    body.theme2 p {
      color: blue;
      font-size: 12px; }
    body.theme2 .bordered {
      border: 3px solid blue; }
    

    现在可以通过向body 标签添加一个类来实现这些主题,例如<body class="theme1"><body class="theme1">

    这是一个 Cloud9 project 显示设置。

    【讨论】:

    • 提示:在styles.scss 中,第一次导入是错误的。不要使用@import 'themes/theme'; 使用@import 'theme'; 所以删除文件夹名称“themes/”,因为_theme.scss 不在该文件夹中
    猜你喜欢
    • 1970-01-01
    • 2021-03-25
    • 2020-01-08
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    相关资源
    最近更新 更多