整 理:晋 哲 时 间:2017-01-06 说 明:使用Sass mixin 的方式将一些固定样式用法封装起来,能够提高样式复用性。
如水平垂直居中的示例:
常用的水平垂直居中方式是使用CSS transform属性或负向margin的方式,将这两种方法集成起来,通过判断是否有宽高值生成对应的样式。
/*定义mixin*/
@mixin center($width: null, $height: null){
position: absolute;
top: 50%;
left: 50%;
@if not $width and not $height{
transform: translate(-50%, -50%);
}
@else if $width and $height{
width: $width;
height: $height;
margin: -($height/2) #{0 0} -($width/2);
}
@else if not $height{
width: $width;
margin-left: -($width/2);
transform: translate(0, -50%);
}
@else{
height: $height;
margin-top: -($height/2);
transform: translate(-50%, 0);
}
}
/*使用*/
.box1{
@include center;
}
.box2{
@include center(200px);
}
.box3{
@include center(null, 300px);
}
.box4{
@include center(200px, 300px);
}