这有点可能使用@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.theme1 或body.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 显示设置。