Sass入门(二)

本文深入讲解Sass的各种控制指令及函数用法,包括条件语句、循环语句、字符串、数字、列表、颜色函数等,同时还介绍了Sass中的Map数据结构及其函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.@if

@if指令是一个SassScript,它可以根据条件来处理样式块,如果条件为true返回一个样式块,反之false返回另一个样式块,在Sass中除了@if之外,还可以配合@else if和@else一起使用

示例:

@mixin blockHidden($boolean : true) {
    @if $boolean {
        @debug "boolean is ${boolean}";
        display : none;
    }
    @else {
        @debug "boolean is ${boolean}";
        display : block;
    }
}

.block {
    @include blockHidden(false);
}

.hide {
    @include blockHidden;
}

编译(sass –watch ./@if.scss:./style.css –style nested)之后:

.block {
  display: block; }

.hide {
  display: none; }

2. for循环

两种方式:$i表示变量 start表示起始值 end表示结束值

@for $i from <start> through <end>
@for $i from <start> to <end>

区别:through 表示包括end这个数,而 to 不包括end这个数

@for $i from 1 through 4 {
    .item-#{$i} {
        width : 2em * $i;
    }
}
.item-1 {
  width: 2em; }

.item-2 {
  width: 4em; }

.item-3 {
  width: 6em; }

.item-4 {
  width: 8em; }
@for $i from 1 to 4 {
    .item-#{$i} {
        width : 2em * $i;
    }
}
.item-1 {
  width: 2em; }

.item-2 {
  width: 4em; }

.item-3 {
  width: 6em; }

@for应用在网格系统生成各个格子class的代码:

$grid-prefix: span !default;
$grid-width : 60px !default;
$grid-gutter: 20px !default;

%grid {
    float: left;
    margin-left: $grid-gutter/2;
    margin-right: $grid-gutter/2;
}

@for $i from 1 through 12 {
    .#{$grid-prefix}#{$i} {
        width: $grid-width * $i + $grid-gutter * ($i - 1);
        @extend %grid;
    }
}

编译之后的代码:

.span1, .span2, .span3, .span4, .span5, .span6, .span7, .span8, .span9, .span10, .span11, .span12 {
  float: left;
  margin-left: 10px;
  margin-right: 10px; }

.span1 {
  width: 60px; }

.span2 {
  width: 140px; }

.span3 {
  width: 220px; }

.span4 {
  width: 300px; }

.span5 {
  width: 380px; }

.span6 {
  width: 460px; }

.span7 {
  width: 540px; }

.span8 {
  width: 620px; }

.span9 {
  width: 700px; }

.span10 {
  width: 780px; }

.span11 {
  width: 860px; }

.span12 {
  width: 940px; }

3. while循环

@while指令也需要SassScript表达式(像其他指令一样),并且会生成不同的样式块,直到表达式为false时停止循环,这个和@for指令很相似,只要@while后面的条件为true就会执行

$types : 5;
$type-width : 20px;

@while $types > 0 {
    .while-#{$types} {
        width: $type-width * $types;
    }

    $types : $types - 1;
}
.while-5 {
  width: 100px; }

.while-4 {
  width: 80px; }

.while-3 {
  width: 60px; }

.while-2 {
  width: 40px; }

.while-1 {
  width: 20px; }

4. each循环

@each循环就是遍历一个列表,然后从表中取出相应的值

@each循环指令的形式:$var 是一个变量名 是一个SassScript表达式,他将返回一个列表值。变量会在列表中做遍历,并且遍历出于变量对应的样式块

@each $var in <list>
$list : adam john wynn mason kuroir vam;

@mixin author-images {
    @each $author in $list {
        .photo-#{$author} {
            background: url('/images/authors/#{$author}.png') no-repeat;
        }
    }
}

.author-bio {
    @include author-images;
}

编译之后的结果:

.author-bio .photo-adam {
  background: url("/images/authors/adam.png") no-repeat; }
.author-bio .photo-john {
  background: url("/images/authors/john.png") no-repeat; }
.author-bio .photo-wynn {
  background: url("/images/authors/wynn.png") no-repeat; }
.author-bio .photo-mason {
  background: url("/images/authors/mason.png") no-repeat; }
.author-bio .photo-kuroir {
  background: url("/images/authors/kuroir.png") no-repeat; }
.author-bio .photo-vam {
  background: url("/images/authors/vam.png") no-repeat; }

5.Sass的函数

主要包括:字符串函数、数字函数、列表函数、颜色函数、Introspection函数、三元函数等

Sass函数之字符串函数

  • unquote($string) : 函数只能删除字符串最前和最后的引号(双引号或单引号),而无法删除字符串中间的引号。如果字符没有带引号,返回的将是字符串本身。
.test1 {
    content: unquote("hello Sass");
}

.test2 {
    content: unquote(hello);
}
.test1 {
  content: hello Sass; }

.test2 {
  content: hello; }
  • quote($string):给字符串添加引号,对于字符串带有引号的情况一律会换为双引号,只能给字符串添加双引号,而且字符串中间有单引号或者空格时,需要用单引号或者双括号括起来,否则编译的时候会出现错误,同时 quote() 碰到特殊符号,比如: !、?、> 等,除中折号 - 和 下划线_ 都需要使用双引号括起,否则编译器在进行编译的时候同样会报错
.test3 {
    content: quote(hello);
}

.test4 {
    content: quote('hi, vam');
}
.test3 {
  content: "hello"; }

.test4 {
  content: "hi, vam"; }
.test3 {
  content: "hello everybody"; }

//Error: $string: ("hello" "everybody") is not a string for `quote'
        on line 80 of ***.scss
  • to-upper-case

该函数将字符串小写字母转换为大写字母,

.test {
    text : to-upper-case(aaa);
    text : to-upper-case(aA-bB);
}
.test {
  text: AAA;
  text: AA-BB; }
  • to-lower-case()
.test {
    text : to-lower-case(ZZZ);
    text : to-lower-case(VAM);
}
.test {
  text: AAA;
  text: AA-BB;
  text: zzz;
  text: vam; }

Sass函数之数字函数

  • percentage($value):将一个不带单位的数转换为百分比值
.footer {
    width : percentage(0.3);
}
.footer {
  width: 30%; }

当然,如果你转换的是带有单位的值,那很不幸,编译都无法通过

  • round($value): 将数值四舍五入,转换为一个最接近的整数
.foer {
    width: round(12.3px);
}
.tor {
    width: round(12.8px);
}
.foer {
  width: 12px; }
.tor {
  width: 13px; }  
  • ceil($value): 将一个数转换成最接近于自己的整数,会将一个大于自身的任何小数转换成大于本身 1 的整数。也就是只做入,不做舍的计算(向上取整)
.foot {
    width: ceil(14.4px);
    height: ceil(14.8px);
}
.foot {
  width: 15px;
  height: 15px; }
  • floor($value): 将一个数除去它的小数部分(向下取整)
.ts1 {
    margin-right: floor(9.8px);
}
.ts1 {
  margin-right: 9px; }
  • abs($value) :返回一个数的绝对值
.ts1 {
    width: abs(-19.8px);
}
.ts1 {
  width: 19.8px;}
  • min($number…): 找出几个数值之间的最小值, 函数中同时出现两种不同类型的单位,将会报错误信息
  • max($number…): 找出几个数值之间的最大值, 函数中同时出现两种不同类型的单位,将会报错误信息
  • random(): 获取随机数
.ts2 {
    width: min(1, 2, 4);
    height: min(2px, 4px, 6px);
    left: random();
    margin-right: max(2px, 8px, 10px);
}
.ts2 {
  width: 1;
  height: 2px;
  left: 0.59485;
  margin-right: 10px; }

Sass函数列表函数

  • length($list):返回一个列表的长度值
.len {
  width: length(2px 3px (1px 2px) 4px) + 'px';
}
.len {
  width: "4px"; }
  • nth($list, \$n): 返回一个列表中指定的某个标签值, n需要大于0,否则会出错哦
.nth {
    width: nth(20px 30px 40px, 2);
    height: nth((30px 40px 50px), 3);
}
.nth {
  width: 30px;
  height: 50px; }
  • join($list1, \$list2, [\$separator]): 将两个列给连接在一起,变成一个列表
>> join(blue,red,comma)    //用comma进行分割
(#0000ff, #ff0000)
.join {
    border: join(1px solid, red); 
}
.join {
  border: 1px solid red; }
  • append($list1, \$val, [\$separator]): 将某个值放在列表的最后

如果没有明确的指定 $separator 参数值,其默认值是 auto。

(1)如果列表只有一个列表项时,那么插入进来的值将和原来的值会以空格的方式分隔。

(2)如果列表中列表项是以空格分隔列表项,那么插入进来的列表项也将以空格分隔;

(3)如果列表中列表项是以逗号分隔列表项,那么插入进来的列表项也将以逗号分隔。

当然,在 append() 函数中,可以显示的设置 $separator 参数,

(1)如果取值为 comma 将会以逗号分隔列表项

(2)如果取值为 space 将会以空格分隔列表项

>> append(10px 20px ,30px)
(10px 20px 30px)
>> append((10px,20px),30px)
(10px, 20px, 30px)
>> append(green,red)
(#008000 #ff0000)
>> append(red,(green,blue))
(#ff0000 (#008000, #0000ff))
  • zip($lists…): 将几个列表结合成一个多维的列表

觉得下面的很形象:

这里写图片描述

>> zip(1px 2px 3px,solid dashed dotted,green blue red)
((1px "solid" #008000), (2px "dashed" #0000ff), (3px "dotted" #ff0000))
  • index($list, \$value): 返回一个值在列表中的位置值,如果指定的值不在列表中(没有找到相应的值),那么返回的值将是 false,相反就会返回对应的值在列表中所处的位置。
>> index(1px solid red, 1px)
1
>> index(1px solid red, solid)
2
>> index(1px solid red, red)
3
>> index(1px solid red,dotted) //列表中没有找到 dotted
false

Sass函数之Introspection

包括的函数有:

  • type-of($value):返回一个值的类型,返回值有,number为数字型,string为字符串型,bool为布尔型,color为颜色型
>> type-of(100)
"number"
>> type-of(100px)
"number"
>> type-of("asdf")
"string"
>> type-of(asdf)
"string"
>> type-of(true)
"bool"
>> type-of(false)
"bool"
>> type-of(#fff)
"color"
>> type-of(blue)
"color"
>> type-of(1 / 2 = 1)
"string"
  • unit($number): 主要是用来获取一个值所使用的单位,碰到复杂的计算时,其能根据运算得到一个“多单位组合”的值,不过只充许乘、除运算
@mixin adjust-charactor($x) {
    @if unit($x) == 'px' {
        $x : $x + 1px;
    }@else if(unit($x) == 'em') {
        $x : $x + 1em;
    }

    position: relative;
    left : $x;
}

.btn {
    @include adjust-charactor(1px);
}
.btn {
  position: relative;
  left: 2px; }
>> unit(100)
""
>> unit(100px)
"px"
>> unit(20%)
"%"
>> unit(1em)
"em"
>> unit(10px * 3em)
"em*px"
>> unit(10px / 3em)
"px/em"
>> unit(10px * 2em / 3cm / 1rem)
"em/rem"
  • unitless($number) : 判断一个值是否带单位,如果不带单位返回的值为true,带单位的话返回的值是false
@mixin adjust-location($x, $y) {
    @if unitless($x) {
        $x : 1px * $x;
    }
    @if unitless($y) {
        $y : 1px * $y;
    }
    position : relative;
    left : $x;
    top : $y;
}

.button {
    @include adjust-location(2, 3);
}
.button {
  position: relative;
  left: 2px;
  top: 3px; }
  • comparable($number-1, \$number-2): 判断两个值是否可以做加减运算
@mixin adjust-comparable($x, $y) {
    @if comparable($x, $y) {
        $x : $x + $y;
    }

    position : asolute;
    left: $x;
}

.pl {
    @include adjust-comparable(3px, 4px);
}
.pl {
  position: asolute;
  left: 7px; }

Sass函数之Miscellaneous函数(三元函数)

@mixin adjust-miscellaneous($condition, $if-true, $if-false) {
    @if($condition, $if-true, $if-false) {
        position: absolute;
        left: $if-true;
    }@else {
        position: relative;
        left: $if-false;
    }
}

.span-tes {
    @include adjust-miscellaneous(true, 3px, 10px);
}
.span-tes {
  position: absolute;
  left: 3px; }

Map

Sass的Map常常被称为数据地图,也有人称其为数组,因为他总是以key:value成对的出现,但其更像是一个JSON数据

$map: (
    default: (
        bgcolor : #fff,
        text-color : #444,
        link-color : #39f
    ),
    primary: (
        bgcolor : #000,
        text-color : #fff,
        link-color : #93f       
    ),
    negative : (
        bgcolor : #f36,
        text-color : #fefefe,
        link-color : #d4e
    )
);

Sass Maps函数

map可以用来管理变量,但要在Sass中获取变量,或者对map做更多有意义的操作,我们必须借助map的函数功能,在Sass中map自身带了七个函数

  • map-get( map,$key):keymap key 不在 $map 中,不会编译此处的 CSS
$socil-colors : (
    dribble: #ea4c89,
    facebook: #3b5998,
    github: #171515,
    google: #db4437,
    twitter: #55acee
);

.btn-dribble {
    color: map-get($socil-colors, dribble);
}
.btn-dribble {
  color: #ea4c89; }
  • map-merge($map1, \$map2): 将两个map合并为一个新的map

  • map-remove($map, \$key) : 从map中删除一个key,返回一个新的map

  • map-keys($map) : 返回map中所有的key
@function colors($color) {
    $names : map-keys($socil-colors);
    @if not index($names, $color) {
        @warn "Waring: `#{$color} is not a valid color name.`";        
    }
    @return map-get($socil-colors, $color);
}

.btn-google {
    color: colors(google);
}
.btn-google {
  color: #db4437; }
//遍历整个map
@each $name in map-keys($socil-colors) {
    .btn-#{$name} {
        color: colors($name);
    }
}

//通过for完成
@for $i from 1 through length(map-keys($socil-colors)) {
    .btn-#{nth(map-keys($socil-colors), $i)} {
        color: colors(nth(map-keys($socil-colors), $i));
    }
}

上面的@each和@for的最终结果一样,编译如下

.btn-dribble {
  color: #ea4c89; }

.btn-facebook {
  color: #3b5998; }

.btn-github {
  color: #171515; }

.btn-google {
  color: #db4437; }

.btn-twitter {
  color: #55acee; }
  • map-values($map):返回map中所有的value
  • map-has-key($map, \$key): 根据给定的key值判断map是否有对应的value值,如果有返回true,否则返回false
@if map-has-key($socil-colors, github) {
    .btn-github {
        color : map-get($socil-colors, github);
    };
}
.btn-github {
  color: #171515; }
//一个color函数
@function color($color) {
    @if not map-has-key($socil-colors, vam) {
        @warn "No color found for `#{$color}` in $social-colors map. Property omitted.";
    }
    @return map-get($socil-colors, $color);
}

.btn-dribble {
    color: color(dribble);
}
.btn-dribble {
  color: #ea4c89; }
  • keywords($args) : 返回一个函数的参数,这个参数可以动态的设置key和value,该函数可以说得上是一个自动创建map的函数,可以通过混用宏或函数参数的方式创建map,参数也是成对存在,其中\$args对应的值就是value
@mixin map($args...) {
    @debug keywords($args);
}

@include map(
  $dribble: #ea4c89,
  $facebook: #3b5998,
  $github: #171515,
  $google: #db4437,
  $twitter: #55acee
);

编译之后的结果:

这里写图片描述

Sass函数之颜色函数

  • RGB颜色函数

RGB颜色只是颜色中的一种表达式,其中R是red代表红色,G是green表示绿色,B是blue代表蓝色,在Sass中为RGB颜色提供了六种函数:

(1) rgb($red, \$green, \$blue ):根据红绿蓝三个值创建一个颜色

>> rgb(200,40,88) //根据r:200,g:40,b:88计算出一个十六进制颜色值
#c82858

(2)rgba($red, \$green, \$blue, \$alpha): 根据红绿蓝和透明度值创建一个颜色

//scss可以使得可以拥有透明值
.rgba {
    color: rgba(#f36, .5);
    background: rgba(orange, .5);
    background-color: rgba(orange, .5);
}
.rgba {
  color: rgba(255, 51, 102, 0.5);
  background: rgba(255, 165, 0, 0.5);
  background-color: rgba(255, 165, 0, 0.5); }
>> rgba(#c82858,.65) //根据#c82858的65%透明度计算出一个rgba颜色值
rgba(200, 40, 88, 0.65)

(3)red($color):从一个颜色中选取其中红色值

$color: #f36;
.body {
    @if red($color) > 50 {
        color: #fff;
    }@else if(red($color) < 50) {
        color: #000;
    }
}

编译之后:

.body {
  color: #fff; }
>> red(#c82858) //从#c82858颜色值中得到红色值 200
200

(4)green($color) : 从一个颜色中获取其中的绿色值

>> green(#c82858) //从#c82858颜色值中得到绿色值 40
40

(5)blue($color): 从一个颜色中获取其中蓝色值

>> blue(#c82858) //从#c82858颜色值中得到蓝色值 88
88

(6)mix($color-1, \$color-2, [weight]): 把两种颜色混合在一起

.mix {
    background-color: mix(#a63, #f36, .7);
}
.mix {
  background-color: #fe3366; }
>> mix(#c82858,rgba(200,40,80,.65),.3) //把#c82858和rgba(200,40,88,.65) 两颜色按比例混合得到一个新颜色
rgba(200, 40, 80, 0.65105)

HSL函数简介

在 Sass 中提供了一系列有关于 HSL 的颜色函数,以供大家使用,其中常用的有 saturation、lightness、adjust-hue、lighten、darken 等等。接下来我们先来了解一下 HSL 颜色函数包括哪些具体的函数,所起的作用是什么:

  • hsl($hue,\$saturation,\$lightness):通过色相(hue)、饱和度(saturation)和亮度(lightness)的值创建一个颜色;
  • hsla($hue,\$saturation,\$lightness,\$alpha):通过色相(hue)、饱和度(saturation)、亮度(lightness)和透明(alpha)的值创建一个颜色;
  • hue($color):从一个颜色中获取色相(hue)值;
  • saturation($color):从一个颜色中获取饱和度(saturation)值;
  • lightness($color):从一个颜色中获取亮度(lightness)值;
  • adjust-hue($color,\$degrees):通过改变一个颜色的色相值,创建一个新的颜色;
  • lighten($color,\$amount):通过改变颜色的亮度值,让颜色变亮,创建一个新的颜色;当颜色的亮度值接近或大于 100%,颜色会变成白色;反之颜色的亮度值接近或小于 0 时,颜色会变成黑色
  • darken($color,\$amount):通过改变颜色的亮度值,让颜色变暗,创建一个新的颜色;当颜色的亮度值接近或大于 100%,颜色会变成白色;反之颜色的亮度值接近或小于 0 时,颜色会变成黑色
  • saturate($color,\$amount):通过改变颜色的饱和度值,让颜色更饱和,从而创建一个新的颜色
  • desaturate($color,\$amount):通过改变颜色的饱和度值,让颜色更少的饱和,从而创建出一个新的颜色;
  • **grayscale( color)desaturate( color,100%);
  • **complement( color)adjusthue( color,180deg);
  • invert($color):反回一个反相色,红、绿、蓝色值倒过来,而透明度不变。

opacity函数

在 CSS 中除了可以使用 rgba、hsla 和 transform 来控制颜色透明度之外,还可以使用 opacity 来控制,只不过前两者只是针对颜色上的透明通道做处理,而后者是控制整个元素的透明度。

在 Sass 中,也提供了系列透明函数,只不过这系列的透明函数主要用来处理颜色透明度:

  • alpha($color) /opacity(\$color):获取颜色透明度值;
  • rgba($color, \$alpha):改变颜色的透明度值;
  • opacify($color, \$amount) / fade-in(\$color, \$amount):使颜色更不透明;
  • transparentize($color, \$amount) / fade-out(\$color, \$amount):使颜色更加透明。

@import

Sass支持CSS3的@规则,以及一些Sass专属的规则,也被称为指令,这些规则在Sass中具有不同的功效

Sass扩展了CSS的@import规则,让它能够引入SCSS和Sass文件。所有引入的SCSS和Sass文件都被合并输出一个单一的CSS文件,另外,被导入的文件中定义的变量或mixins都可以在主文件中使用。

Sass会在当前目录下寻找其他Sass文件,如果是Rack、Rails或者Merb环境中则是Sass文件目录,也可以通过:load_paths选项或在命令行中使用–load-path选项来指定额外的搜索目录。

@import根据文件名引入,默认情况下,它会寻找Sass文件并直接引入,但是在极少数情况下,它会编译成CSS的@import规则:

  • 如果文件的扩展名为.css
  • 如果文件名是以http://开头
  • 如果文件名是url()
  • 如果@import包含了任何媒体查询(media queries)

如果上述情况都没有出现,并且扩展名是 .scss 或 .sass, 该名称的 Sass 或 SCSS 文件就会被引入。 如果没有扩展名, Sass 将试着找出具有 .scss 或 .sass 扩展名的同名文件并将其引入。

@media

Sass中的@media和CSS的使用规则一样的简单,但它有另外一个功能,可以嵌套在CSS规则中,有点类似JS的冒泡功能一样,如果在样式中使用@media指令,它将冒泡到外面

.sidebar {
    width: 300px;
    @media screen and (orientation: landscape) {
        width: 500px;
    }
}

编译之后:

.sidebar {
  width: 300px; }
  @media screen and (orientation: landscape) {
    .sidebar {
      width: 500px; } }

@extend

@extend 不止扩展类选择器,还可以扩展任何选择器,这里就不详细描述了,可查看关于继承部分的例子(http://blog.youkuaiyun.com/dear_mr/article/details/70477161

.error {
    border: 1px #f00;
    background-color: #fdd;
}

.seriousError {
    @extend .error;
    color: red;
}

编译之后的结果:

.error, .seriousError {
  border: 1px #f00;
  background-color: #fdd; }

.seriousError {
  color: red; }

@at-root

从字面上理解就是跳出根元素,当选择器嵌套多层之后,想让某个选择器跳出,此时就可以用@at-root

.a {
    color: red;
    .b {
        color: orange;
        .c {
            color: black;
            @at-root .d {
                color: green;
            }
        }
    }
}

编译之后的结果:

.a {
  color: red; }
  .a .b {
    color: orange; }
    .a .b .c {
      color: black; }
      .d {
        color: green; }

@debug

@debug是在Sass中用来调试的,当Sass代码使用了@debug命令之后,Sass代码在编译出错之后,在命令端口输出设置的bug

    @debug 10em + 12em;

这里写图片描述

@warn

@warn与@debug功能类似,用来帮助我们更好的调试Sass

@mixin adjust-location($x, $y) {
    @if unitless($x) {
        $x : 1px * $x;
    }
    @if unitless($y) {
        $y : 1px * $y;
    }
    position : relative;
    left : $x;
    top : $y;
}

@error

@error和@warn、@debug功能如出一辙

.error {
    @error "test error!";   
}

最近更新的比较慢, ^_^,看来还是得快点学习啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值