Sass 中的 @mixin 很简单对吧,他能帮我们处理css中哪些问题呢?
1. 项目中经常会遇到超出一行/多行后省略号,我们可以用@mixin 这样处理
// 超出一行显示更多
@mixin f-single-line{
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
// 超出两行以上显示更多
@mixin f-lines($lines) {
word-break: break-word;
display: -webkit-box;
-webkit-box-orient: vertical;
box-orient: vertical;
-webkit-line-clamp: @lines;
line-clamp: $lines;
overflow: hidden;
text-overflow: ellipsis;
}
// 使用
p{
color: pink;
@include f-single-line();
}
p{
color: pink;
@include f-lines(3);
}
2. 简化媒体查询
在css中,如果我们想实现一个适配ipad、phone、桌面端的媒体查询是这样写的
@media screen and (max-width: 767px) {
/* 样式代码 */
}
@media screen and (min-width: 768px) and (max-width: 992px) {
/* 样式代码 */
}
@media screen and (min-width: 993px) {
/* 样式代码 */
}
难道我们在每写一个div都要搞这么一堆代码吗?
我们可以用sass的 @mixin 这样做
@mixin media-query($type) {
@if $type == 'mobile' {
@media only screen and (max-width: 767px) {
@content;
}
}
@else if $type == 'tablet' {
@media only screen and (min-width: 768px) and (max-width: 992px) {
@content;
}
}
@else if $type == 'desktop' {
@media only screen and (min-width: 993px) {
@content;
}
}
}
//使用
.some-class {
/\* 手机端样式 */
@include media-query('mobile') {
/* 手机端样式代码 \*/
}
/\* 平板样式 */
@include media-query('tablet') {
/* 平板样式代码 \*/
}
/\* 桌面端样式 */
@include media-query('desktop') {
/* 桌面端样式代码 \*/
}
}
这里的 @content 相当于插槽可以把你 函数
内写的内容放到content的位置
3.同理2 可以用它调整我们应用中不同语言的样式
一般的区分我们应用不同语言的标识是在html上的
<html lang='em_us'>
xxxxxxx
<html>
如果不用sass我们的代码是这样的,整个项目中可能会有n多个地方要写,假如以后我们要改lang='em_us'
为 lang='em
,因为js中也可能会有lang='em_us'
所以全局替换并不好做
div{
[lang='em_us'] & {
color: pink;
}
}
那我们就可以用sass 这样做
// 定义
@mixin lang_en_us() {
[lang='en_us'] & {
@content
}
}
// 使用
@include lang_en_us(){
color: pink;
}
这样我们以后修改 lang='em_us'
为 lang='em
只需要换一个地方就好了。
总结:我们可以通过这三个例子来演变出更多的功能,希望这篇文章可以帮助到大家!
也欢迎大家关注我的开源项目基于AIGC的数据库查询工具,一起学习一切成长 github.com/alibaba/Cha…