嗨,我仍然是SASS的新手,也没有编程大师。
我有十个旁边的元素,所有元素都需要根据类名不同的背景颜色。
我查看了SASS文档,我无法弄明白。
我想说如果旁边有一个类名为x make background color x,如果旁边有一个类名为y make background color y等
这样做有效吗?
谢谢你们,对不起,如果这是一个简单的问题。
答案 0 :(得分:0)
这只取决于你想要做多少打字。您可以创建一个背景混合并将其包含在旁边的CSS规则中,但这是否真的有必要?
如果是......
@mixin bg($color) {
background: $color;
}
aside#foo {
@include bg(#fff);
}
答案 1 :(得分:0)
如果您使用的颜色没有“标准”名称(或者类的名称根本不是颜色,例如.products = blue,addresses = red),列表列表是你想要的:
$colors:
( black #000
, white #FFF
, red #F00
, green #0F0
, blue #00F
);
@each $i in $colors {
aside.#{nth($i, 1)} {
background: nth($i, 2);
}
}
输出:
aside.black {
background: black; }
aside.white {
background: white; }
aside.red {
background: red; }
aside.green {
background: lime; }
aside.blue {
background: blue; }
如果您使用标准关键字的颜色,这可能有效:
$colors2: black, white, red, green, blue;
@each $i in $colors2 {
aside.#{$i} { background: $i; }
}
输出(虽然这似乎仅适用于--style debug
,但使用--style compress
会产生错误..很奇怪):
aside.black {
background: black; }
aside.white {
background: white; }
aside.red {
background: red; }
aside.green {
background: green; }
aside.blue {
background: blue; }
答案 2 :(得分:-1)
“如果旁边有一个类名为x make background color x如果在旁边有一个类名为y make background color y”则转换为以下CSS:
aside.x {background-color: x}
aside.y {background-color: y}
您是否有理由使用SASS?它是否使它变得动态,以便您可以在不更新CSS的情况下添加您想要的任何类? (如果是这样,SASS无法实现,因为SASS代码编译为CSS并且之后不会更改。)
要完成这项工作,你必须使用JS(jQuery):
$('aside').each(function () {
$(this).css('background-color', $(this).attr('class'));
});
编辑:你可以在SASS中使用循环来生成大量的类和相应的背景颜色。