混入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();
}
相关推荐
明远湖之鱼1 小时前
浅入理解跨端渲染:从零实现 React DSL 跨端渲染机制
前端·react native·react.js
悟忧1 小时前
规避ProseMirror React渲染差异带来的BUG
前端
小皮虾1 小时前
小程序云开发有类似 uniCloud 云对象的方案吗?有的兄弟,有的!
前端·javascript·小程序·云开发
Android疑难杂症2 小时前
鸿蒙Notification Kit通知服务开发快速指南
android·前端·harmonyos
T___T2 小时前
全方位解释 JavaScript 执行机制(从底层到实战)
前端·面试
阳懿2 小时前
meta-llama-3-8B下载失败解决。
前端·javascript·html
Qinana2 小时前
🌊 深入理解 CSS:从选择器到层叠的艺术
前端·css·程序员
IT_陈寒2 小时前
Python 3.12新特性实测:10个让你的代码提速30%的隐藏技巧 🚀
前端·人工智能·后端
闲人编程2 小时前
从零开发一个简单的Web爬虫(使用Requests和BeautifulSoup)
前端·爬虫·beautifulsoup·bs4·web·request·codecapsule
紫小米2 小时前
Vue 2 和 Vue 3 的区别
前端·javascript·vue.js