SASS mixin 根据 body 是否有 class(或 grand parent)包含代码块
SASS mixin to include code block depending on whether body has class (or grand parent)
我正在尝试创建一个 mixin 允许我根据 body 是否具有特定 class.
灵活地编写代码块
@mixin when($class) {
body.#{$class} & {
@content;
}
}
用例
#hero {
@include when('theme--dark') {
span {
content: 'Good Evening';
}
}
}
#hero {
@include when('page-landing') {
button.cta {
padding: 3rem 5rem;
font-size: 3rem;
background-color: $green;
}
}
}
如果能做到以下就更好了
@mixin when($parent, $class) {
#{$parent}.#{$class} & {
@content;
}
}
#hero {
@include when('body','page-landing') {
button.cta {
padding: 3rem 5rem;
font-size: 3rem;
background-color: $green;
}
}
}
以前的代码都行不通,甚至不确定语法,但想知道是否可以生成类似的东西,感谢任何帮助,谢谢!
虽然您的方法绝对没问题,但这里有一个稍微简洁的实现,它在您要检查的选择器数量方面提供了更多的灵活性。
@mixin when($selectors...) {
$n: "";
@each $selector in $selectors {
$n: str-insert($n, "#{$selector}", str-length($n) + 1);
}
#{$n} {
@content;
}
}
#hero {
@include when('body', '[dark-mode=true]', '.primary') {
color: #fff;
}
}
我正在尝试创建一个 mixin 允许我根据 body 是否具有特定 class.
灵活地编写代码块@mixin when($class) {
body.#{$class} & {
@content;
}
}
用例
#hero {
@include when('theme--dark') {
span {
content: 'Good Evening';
}
}
}
#hero {
@include when('page-landing') {
button.cta {
padding: 3rem 5rem;
font-size: 3rem;
background-color: $green;
}
}
}
如果能做到以下就更好了
@mixin when($parent, $class) {
#{$parent}.#{$class} & {
@content;
}
}
#hero {
@include when('body','page-landing') {
button.cta {
padding: 3rem 5rem;
font-size: 3rem;
background-color: $green;
}
}
}
以前的代码都行不通,甚至不确定语法,但想知道是否可以生成类似的东西,感谢任何帮助,谢谢!
虽然您的方法绝对没问题,但这里有一个稍微简洁的实现,它在您要检查的选择器数量方面提供了更多的灵活性。
@mixin when($selectors...) {
$n: "";
@each $selector in $selectors {
$n: str-insert($n, "#{$selector}", str-length($n) + 1);
}
#{$n} {
@content;
}
}
#hero {
@include when('body', '[dark-mode=true]', '.primary') {
color: #fff;
}
}