前言
Scss时CSS的一些扩展,本篇主要关于介绍变量的创建,一些逻辑结构,以及重用样式;
正文
创建变量:
<style type='text/scss'>
$color:red;
h1{
background:$color;
}
</style>
<h1>我的背景是红的</h1>
<!--要设置type="text-scss",在变量面前使用$,表示变量;引用时也要加$;
嵌套设置:
<style type="text-scss">
$h1-color:red;
$div-color:yellow;
#div{
background:$div-color;
h1{
background:$h1-color;
}
}
</style>
<div id="div">
<h1>我是红的</h1>
<h2>我是黄的</h2>
</div>
外层为父标签的样式,内层为子标签样式;
创建可重用CSS:
<style type="text/scss">
@mixin border-radius($s){
-webkit-border-radius: $s;
-moz-border-radius: $s;
-ms-border-radius:$s;
border-radius: $s;
}
div{
@include border-radius(50%);
width:50px;
height:50px;
background:red;
}
</style>
<div></div>
样式前加@mixin表示是一个可重用CSS,类似函数,在引用时在函数前加@include并加相应参数;
@if @else:
<style type="text/scss">
@mixin color($co){
@if $co == red{
background:$co;}
@else if $co == $co{
background:yellow;}
@else {
background:red;}
}
div{
@include color(red);
width:50px;
height:50px;
}
</style>
<div></div>
注意便两千加$;
@for:
<style type="text/scss">
@for $i from 1 through 2{
.text-#{$i}{font-size:$i*10px}
}
</style>
<span class="text-1">第一个</span>
<span class="text-2">第二个</span>
through表示从一到二,也可以换成to,表示从一到一,不包括结束的数字;
#{$i}表示将变量文本化;
@each遍历集合:
<style type="text/scss">
@each $i in red,yellow,blue{
.#{$i}-box{background:$i;height:50px;}
}
</style>
<div class="red-box"></div>
<div class="yellow-box"></div>
<div class="blue-box"></div>
map遍历键对值:
<style type="text/scss">
$colors:(co1:red,co2:yellow,co3:blue);
@each $key,$i in $colors{
.#{$key}-box{background:$i;height:50px;}
}
</style>
<div class="co1-box"></div>
<div class="co2-box"></div>
<div class="co3-box"></div>
each的第一个值表示键第二个表示值;
while:
<style type="text/scss">
$i:0;
@while $i<2{
.text-#{$i}{font-size:$i*10px}
$i:$i+1;
}
</style>
<span class="text-1">第一个</span>
<span class="text-2">第二个</span>
scss的文件可以通过@import加文件名导入;
继承:
<style type="text/scss">
.box1{
width:50px;
height:50px;
background:red;
}
.box2{
@extend .box1;
border-radius:50%;
background:yellow;
}
</style>
<div class="box1"></div>
<div class="box2"></div>
@extend表示继承所有的属性,可以继续添加,也可以通过重名的方式来重写属性;