用 SASS 将类名替换为 CSS

  • 本文关键字:替换 CSS SASS css sass
  • 更新时间 :
  • 英文 :


我有几个类名,它们都99%相同 - 除了背景图像。类名始终与图像文件名匹配:

示例(见.icon_hero_rank-19(:

.brawler .rank.icon_hero_rank-19 {
background-image: url("/images/ranks/icon_hero_rank-19.png");
position: absolute;
top: 85%;
left: 0;
width: 40px;
height: 45px;
line-height: 45px;
background-size: contain;
display: inline-block;
text-align: center;
font-weight: normal;
vertical-align: middle;
font-family: "BrawlStarsDeputy";
color: white;
font-size: 1.5rem;
text-shadow: 0px 3px 2px rgba(0, 0, 0, 0.8);
letter-spacing: 1px;
z-index: 10;
}

问题:

那么有没有办法在我的 CSS 中将类名作为变量重用,或者你有什么建议?

可以为选择器和 CSS 属性使用预定义的变量名称,如下所示:

$icon-list: (
icon_hero_rank-00,
icon_hero_rank-19
);
@each $icon in $icon-list {
.brawler .rank.#{$icon}{
background-image: url("/images/ranks/#{$icon}.png");
position: absolute;
top: 85%;
left: 0;
width: 40px;
height: 45px;
line-height: 45px;
background-size: contain;
display: inline-block;
text-align: center;
font-weight: normal;
vertical-align: middle;
font-family: "BrawlStarsDeputy";
color: white;
font-size: 1.5rem;
text-shadow: 0px 3px 2px rgba(0, 0, 0, 0.8);
letter-spacing: 1px;
z-index: 10;
}
}

当然,你可以使用 for 循环

看看这个

$string-template: "icon_hero_rank-";

$start: 0;
@for $i from 1 through 8 {

.brawler .rank.#{$string-template}#{$i+$start} {
background-image: url("/images/ranks/#{$string-template}#{$i+$start}.png");
position: absolute;
top: 85%;
left: 0;
width: 40px;
height: 45px;
line-height: 45px;
background-size: contain;
display: inline-block;
text-align: center;
font-weight: normal;
vertical-align: middle;
font-family: "BrawlStarsDeputy";
color: white;
font-size: 1.5rem;
text-shadow: 0px 3px 2px rgba(0, 0, 0, 0.8);
letter-spacing: 1px;
z-index: 10;
}

}

基于您已经发布的答案,Kentor,您可以使用属性选择器将所有共享样式仅设置一次,然后在@each函数中设置背景图像,从而大大压缩已编译的 CSS。

.brawler div[class*="icon_hero_"].rank {
position: absolute;
top: 85%;
left: 0;
width: 40px;
height: 45px;
line-height: 45px;
background-size: contain;
display: inline-block;
text-align: center;
font-weight: normal;
vertical-align: middle;
font-family: "BrawlStarsDeputy";
color: white;
font-size: 1.5rem;
text-shadow: 0px 3px 2px rgba(0, 0, 0, 0.8);
letter-spacing: 1px;
z-index: 10;
}
$icon-list: (
rank-00,
rank-19
);
@each $icon in $icon-list {
.brawler div[class$="#{$icon}"].rank{
background-image: url("/images/ranks/#{$icon}.png");
}
}

这样,您就不会在样式表中重复多次共享样式。

最新更新