我想使用主题设置文件为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规则来完成?
答案 0 :(得分:3)
使用@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}
会创建一个类似body.theme1
或body.theme2
的选择器,具体取决于$theme-name
变量的当前值。
在此演示中,我在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。