04-Scss-Mixin混入的使用

本文介绍了如何在SCSS中利用mixin(混入)技术,实现文本溢出省略的代码复用,并结合媒体查询进行适应不同宽度的需求。通过`singleline-ellipsis` mixin,简化了`.text`和`.content-text`类的选择器,展示了灵活的参数传递和样式调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过 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 —

继续阅读 05-Scss-媒体查询与Mixin的配合使用 >>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值