此前我使用scss,仅仅是为了用而用,只知道它的嵌套写法给我们带来了很多方便,即美观也不用手动嵌套。
但其实scss有很多其他的优点才是精髓,这里详细说一下自己使用scss时,用到的样式复用方法。欢迎补充。
文章目录
一、引入外部公共样式变量
- 公共变量scss文件–index.scss
- 引入及调用公共变量
二、@mixin的使用
最主要的好处是可以像函数一样传参,自定义样式模块
下面用一些简单的例子说明使用方法
1、不传参的@mixin示例
flex
的左右以及上下居中的复用
- 定义mixin
- 调用mixin
2、传参的@mixin示例
文本/图片样式的复用,变量使用
$
定义
- 定义mixin
mixin简易示例代码-定义 - 调用mixin
3、灵活利用默认值
@mixin定义变量的同时,设置默认值(与函数相同)
- 定义mixin
- 调用mixin
- 命名调用mixin
方便维护,和不用在乎数量(变量多的时候使用)
三、常用@mixin样式模版举例
1、省略号mixin
/*文本格式化,超出范围,显示省略号*/
@mixin text-overflow($width:100%,$line:1) {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
display:-webkit-box;
-weblit-box-orient:vertical;
width: $width;
-weblit-line-clamp:$line;
}
2、flex布局mixin
scss使用逻辑运算,加上
@if
即可,其他同理
/**
*默认flex样式水平,垂直居中
* 1、$flex-wrap: null -- 清空所有对齐样式
* 2、$direction:... -- 水平排/垂直排
* 3、...
*/
@mixin flex-center($direction:row,$justify:center,$align:center,$flex-wrap: null) {
display: flex;
@if ($flex-wrap != null) {
flex-wrap: $flex-wrap;
}
@if ($direction!=null) {
flex-direction: $direction;
}
@if ($justify!=null) {
justify-content: $justify;
}
@if ($align!=null) {
align-items: $align;
}
3、绝对定位
直接写4个数字,简化代码
/*绝对定位 参数顺序:上右下左*/
@mixin positionAbsolute($top:null,$right:null,$bottom:null,$left:null) {
position: absolute;
@if ($left!="" & & $left!=null) {
left: $left;
}
@if ($right!="" & & $right!=null) {
right: $right;
}
@if ($top!="" & & $top!=null) {
top: $top;
}
@if ($bottom!="" & & $bottom!=null) {
bottom: $bottom;
}
4、圆形块
简化2次尺寸和圆角,内容水平垂直居中
/* 圆形盒子 */
@mixin circle($size: 11px,$bg: #fff) {
border-radius: 50%;
width: $size;
height: $size;
line-height: $size;
text-align: center;
background: $bg;
}
5、滚动条样式(伪类)
/**
*定义滚动条样式 圆角和阴影不需要则传入null
* 1、$outColor -- 滚动条颜色
* 2、$innerColor -- 滑块颜色
* 3、$height -- 滚动条宽高、圆角
* 4、$width
* 5、$radius
* 6、$shadow -- 阴影
*/
@mixin scrollBar($width:10px,$height:10px,$outColor:$bgColor,$innerColor:$bgGrey,$radius:5px,$shadow:null) {
/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
&::-webkit-scrollbar {
width: $width;
height: $height;
background-color: $outColor;
}
/*定义滚动条轨道 内阴影+圆角*/
&::-webkit-scrollbar-track {
@if ($shadow!=null) {
-webkit-box-shadow: $shadow;
}
@if ($radius!=null) {
border-radius: $radius;
}
background-color: $outColor;
}
/*定义滑块 内阴影+圆角*/
&::-webkit-scrollbar-thumb {
@if ($shadow!=null) {
-webkit-box-shadow: $shadow;
}
@if ($radius!=null) {
border-radius: $radius;
}
background-color: $innerColor;
border: 1px solid $innerColor;
}
}
四、总结
基本语法是:变量用$
、方法用'@'
( @mixin
、@if
、@extend
… )
mixin里可以嵌套mixin
重点是灵活利用变量
万事不顺,查文档:sass官方文档
如有建议和疑问可联系
QQ:1017386624
邮箱:1017386624@qq.com