有两种方法可以做到这一点。它们都包含 mixin。
meta.load-css
sass:meta feature 让您可以随心所欲。
假设你有这个带有主题的 scss 文件:
//theme/_code.scss
$border-contrast: false !default;
code {
background-color: #6b717f;
color: #d2e1dd;
@if $border-contrast {
border-color: #dadbdf;
}
}
您可以像这样将该代码包含在另一个 scss 文件中:
// other-theme.scss
@use "sass:meta";
body.dark {
@include meta.load-css("theme/code",
$with: ("border-contrast": true));
}
这将导致以下css:
body.dark code {
background-color: #6b717f;
color: #d2e1dd;
border-color: #dadbdf;
}
您可以在此处阅读有关此功能的更多信息
老式的混入
但是如果你使用mixin and include,你基本上可以做同样的事情。
所以,假设你有这个类要导入到另一个类中:
.title {
font-size: 2em;
font-weight: bold;
}
还有另一个主题的 sass 文件:
.dark-theme {
.title {
font-size: 2em;
font-weight: bold;
color: white;
}
}
您可以使用 scss mixin 并将其导入到两个文件中:
mixin.scss
@mixin shared-items() {
.title {
font-size: 2em;
font-weight: bold;
}
}
然后,在主题文件中:
白色主题.scss
@import './mixin.scss';
/* will be included as is without a parent class */
@include shared-items;
dark-theme.scss
@import './mixin.scss';
/* will be included inside the dark-theme class */
.dark-theme {
.title {
color: white;
}
@include shared-items;
}
这将生成这个 css:
.title {
font-size: 2em;
font-weight: bold;
}
.dark-theme {
.title { color: white; }
.title {
font-size: 2em;
font-weight: bold;
}
}
请注意,您还可以将参数传递给 mixin 并将它们用作函数。
因此,您可以轻松传递颜色并将它们与主题变量一起使用。
例如:
# an example of giving a color to a placeholder mixin:
@mixin nk-placeholder($color: #C4C4CC) {
&::-webkit-input-placeholder {
color: $color;
font: inherit;
}
&::-moz-placeholder {
color: $color;
font: inherit;
}
&:-ms-input-placeholder {
color: $color;
font: inherit;
}
&:-moz-placeholder {
color: $color;
font: inherit;
}
&::placeholder {
color: $color;
font: inherit;
}
}
# same thing as above
@mixin shared-items($text-color: black) {
.title {
font-size: 2em;
font-weight: bold;
color: $text-color;
}
}
.white-theme {
@include shared-items;
}
.dark-theme {
@include shared-items(white);
}