用SASS

时间:2017-07-27 22:24:31

标签: 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中重用类名作为变量或者你推荐什么?

3 个答案:

答案 0 :(得分:1)

可以为选择器和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;
    }
}

答案 1 :(得分:1)

当然,你可以使用for循环

Take a look at this

$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;
}



}

答案 2 :(得分:1)

根据您已经发布的答案,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");
    }
}

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