我正试图创建一个小的自定义图标库,用于我的网站,如下所示:
它适用于单个图标,但我不想为我要使用的每个图标都写它。所以我尝试使用SASS/SCSS来做一些更简单的事情:
.icon {
height: 4.5rem;
width: 4.5rem;
display: inline-block;
background-size: contain;
background-repeat: no-repeat;
}
.google-icon {
background: url('../icons/icon.png');
@extend icon;
}
它生成这个CSS:
.icon, .google-icon {
height: 4.5rem;
width: 4.5rem;
display: inline-block;
background-size: contain;
background-repeat: no-repeat;
}
.google-icon {
background: url("../icons/icon.png");
}
它不起作用,背景大小和背景重复值被覆盖了,我不知道是什么,但它们不适用,我可以看到我一直用来插入图标的i元素,在开发工具中,我可以查看我使用的图像,但由于这两个属性被覆盖,它无法正确显示。如果我使用@Mixin,效果很好,但据我所知,最好尽可能使用@extend。
代码段中的几个问题:
.google-icon {
background: url('../icons/icon.png');
@extend icon;
}
您的扩展应该是
@extend .icon
,请参阅">">您正在使用
background: url('../icons/icon.png')
,而您应该使用background-image: url('../icons/icon.png')
。
background
是简写,这意味着它是为多个属性提供值的一种方式。(例如:背景图像、背景大小、背景位置、背景颜色等。(。这一行覆盖了您以前的规则。
为了避免使用@extend
,您可以使用不同的方法:
CSS[attribute ^=value]选择器
[class^=icon-] {
height: 4.5rem;
width: 4.5rem;
display: inline-block;
background-size: contain;
background-repeat: no-repeat;
}
.icon-google { // The classname will start with icon-
background-image: url('../icons/icon.png'); // background-image instead of background
}
通过使用[class^=icon-]
,将选择每个类以icon-
开头的html元素
这样,如果所有图标类名都以icon-
开头,就像icon-google
一样,则不需要任何扩展。