混入mixins

sass语法

定义 :@mixins 名称(参数1[: 默认值], 参数2[: 默认值] ......) {

// 样式

}

引用 :@include 名称(参数1, ...);

示例

css 复制代码
// 定义mixin,$color参数设置默认值为red
@mixins scrollbar($color: red, $width) {
    ::-webkit-scrollbar {
        width: $width;
    }
    ::-webkit-scrollbar-thumb {
        background-color: $color;
    }
}

// 引用mixin,并传参
.container {
    @include scrollbar(blue, 12px);
}

其他支持的特性

  • 定义mixin支持参数变量(类似js的可变参数,三个点...)(@mixins 名称(参数名...)
  • 引用mixin支持关键词参数,这样可以打乱参数的顺序(@include 名称(参数名1: 参数值1...))
css 复制代码
// 参数变量
@mixins shadows($shadow...) {
    box-shadow: $shadows;
}
// 参数变量的mixin引用
.container {
    @include shadows(0px 3px 6px #333, 2px 5px 8px #666);
}

// 关键词参数引用mixin,可以打乱参数顺序
.container {
    @include scrollbar($width: 12px, $color: blue);
}

less语法

定义

1,正常已定义的类或id选择器

2,选择器后面接小括号。也可以传参,支持默认值(参数1[: 默认值], 参数2[: 默认值] ......)

引用 :.类名(参数1...);

示例

css 复制代码
// 普通选择器,可以当做mixin被引用
.scrollbar {
    ::-webkit-scrollbar {
        width: 12px;
    }
    ::-webkit-scrollbar-thumb {
        background-color: red;
    }
}

// 带参数和默认值的mixin选择器
.scrollbar2(@color: red, @width) {
    ::-webkit-scrollbar {
        width: @width;
    }
    ::-webkit-scrollbar-thumb {
        background-color: @color;
    }
}


.container {
    width: 100px;
    .scrollbar(); // 引用普通mixins
    .scrollbar2(blue, 12px);  // 引用带参数的mixins,传参
}

其他支持的特性

  • 引用mixins时设置!important(相当于将mixin选择器中的所有属性都设置成!important)
  • 定义mixins时设置mixins守卫(@mixins when( 表达式 ))(mixins守卫与media查询类似,按需加载,并不是if、else按条件执行)
  • mixin定义时赋值给一个变量,将变量作为别名;整个mixin调用可以使用别名称为变量调用(通过@alias属性名、属性值通过点来调用)
css 复制代码
// 普通选择器,可以当做mixin被引用
.scrollbar {
    ::-webkit-scrollbar {
        width: 12px;
    }
}

// 引用mixins使用important
.container {
    .scrollbar() !important;
}


// mixins守卫
@width: 10;
.scrollbar when(@width < 10) {
    // ...
}
.scrollbar when(@width > 10) {
    // ...
}

// 赋值变量做别名
@scroll: .scrollbar();
// 引用别名的mixin
.container {
    @scroll;
}

// mixin变量调用
#main() {
    .scrollbar() {
        ::-webkit-scrollbar {
            width: 12px;
        }
    }
}
.container {
    @alias: #main.scrollbar();
}
相关推荐
曼巴UE51 小时前
UE FString, FName ,FText 三者转换,再次学习,官方文档理解
服务器·前端·javascript
行走的陀螺仪2 小时前
高级前端 Input 公共组件设计方案(Vue3 + TypeScript)
前端·javascript·typescript·vue·组件设计方案
一颗不甘坠落的流星2 小时前
【Antd】基于 Upload 组件,导入Json文件并转换为Json数据
前端·javascript·json
LYFlied2 小时前
Vue2 与 Vue3 虚拟DOM更新原理深度解析
前端·javascript·vue.js·虚拟dom
Lucky_Turtle2 小时前
【Node】npm install报错npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
小飞侠在吗2 小时前
vue shallowRef 与 shallowReacitive
前端·javascript·vue.js
惜分飞3 小时前
sql server 事务日志备份异常恢复案例---惜分飞
前端·数据库·php
GISer_Jing3 小时前
WebGL实例化渲染:性能提升策略
前端·javascript·webgl
烟锁池塘柳04 小时前
【技术栈-前端】告别“转圈圈”:详解前端性能优化之“乐观 UI” (Optimistic UI)
前端·ui