通过 css 编写“文本在一行内显示,如果超出一行则显示省略号”这样的需求时,编写的代码如下:
.text {
width: 600px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.content-text {
width: 1000px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
对于上面的 text 和 content-text 两个类选择器,有部分共用的代码,所以最好对其进行抽离合并。
在 scss 中,不能如之前所学的部分直接封装公共代码,这里引入 mixin 混入,方便对代码进行抽离。
@mixin singleline-ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.text {
width: 600px;
@include singleline-ellipsis;
}
.content-text {
width: 1000px;
@include singleline-ellipsis;
}
对抽离出来的命名为 singleline-ellipsis,在需要使用的代码内部通过 @include + 名字
实现引入。
当然,也可以单独形成一个文件,再通过 @import
进行引入。
此外,mixin 接收参数的传递,在使用时,可以直接把参数作为变量赋值给内部属性。
_mixins.scss
@mixin singleline-ellipsis($width) {
width: $width;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
main.scss
@import 'mixins';
.text {
@include singleline-ellipsis(600px);
}
.content-text {
@include singleline-ellipsis(1000px);
}
编译成功的css代码:
.text {
width: 600px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.content-text {
width: 1000px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}/*# sourceMappingURL=main.css.map */
— END —