Home  >  Article  >  Web Front-end  >  Sass-Maybe you want to play with CSS (Part 2)

Sass-Maybe you want to play with CSS (Part 2)

WBOY
WBOYOriginal
2016-08-30 09:21:121121browse

Have a clear conscience and encourage each other!

sass-Maybe you want to play with CSS (Part 1)

The previous article mainly introduced some basic features of sass. In the next article, we will mainly write some of our commonly used Sass control commands, functions and rules.

sass advanced

Control commands

Friends who have read the previous article may find that @if, @else, @each, etc. appear in some codes. Friends who are familiar with JS conditional statements and loops will better understand the functions of these control commands. These control commands are part of Sass. An important part of.

@if,@else

@if@else is a simple SassScript that processes style blocks based on conditions. If the condition of if is true, then the if style block is called, otherwise the else style block is called. A simple code example

@mixin GOD($SHOW:true) {
  @if $SHOW {
      display: block;
    }
    @else {
      display: none;
    }
}

.block {
  @include GOD;
}

.hidden{
  @include GOD(false);
}

In the above code, because the .block call does not pass the parameter if, it is judged to be true, and the code block in the if is called. When .hidden calls GOD, the parameter false is passed in, and false overwrites the original default parameters. If is judged to be false, call The code in the else code block.

@for loop

To give an example, we may write a bootstrap-like raster network, col-1, col-2, col-3. . . If the number is large at this time, it may be more troublesome to write, so with sass we can write like this

@for $i from 1 through 5 { //生成到col-5
  .col-#{$i} { width: 2rem * $i; }
}

@for $i from 1 to 5 { //生成到col-4
  .col-#{$i} { width: 2rem * $i; }
}

The grammar rule is @for variable from starting to/through ending, it has two methods to and through to describe "to", the difference between them is that 1 to 5 finally generates only .col-4 while 1 through 5 is When generated to col-5, to will be one less than through.

@while loop

The while loop is similar to the loop in JS. Let’s look at an example where the @for loop has the same effect as above

$number: 5;
$number-width: 20px;

@while $number > 0 {
    .col-#{$number} {
        width: $mumber-width * $number;
    }
    $number: $number - 1;
}

@each loop

$list: adam john wynn mason kuroir;//$list 就是一个列表

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

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

sass @rules

@import

Sass extends the CSS @import rule to allow it to import SCSS and Sass files. All incoming SCSS and Sass files are merged and output into a single CSS file. In addition, variables or mixins defined in the imported file can be used in the main file.

@import "foo.css";
@import "foo" screen;
@import "http://foo.com/bar";
@import url(foo);

@media

The @media directive in Sass is as simple as CSS rules, but it has another function and can be nested within CSS rules. Somewhat similar to the bubbling function of JS, if you use the @media directive in a style, it will bubble to the outside.

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

@extend

@extend in Sass is used to extend selectors or placeholders.

.error {
  border: 1px #f00;
  background-color: #fdd;
}
.error.intrusion {
  background-image: url("/image/hacked.png");
}
.seriousError {
  @extend .error;
  border-width: 3px;
}

@at-root

@at-root literally means jumping out of the root element. When you have multiple nested selectors and want a certain selector to pop out, you can use @at-root.

.a {
  color: red;

  .b {
    color: orange;

    .c {
      color: yellow;

      @at-root .d {
        color: green;
      }
    }
  }  
}

Compiled results

.a {
  color: red;
}

.a .b {
  color: orange;
}

.a .b .c {
  color: yellow;
}

.d {
  color: green;
}

@debug, @warn, @error

These three commands are used for debugging in Sass. After you use these instructions in the Sass source code, when the Sass code compiles and compiles errors, the command terminal will output the bug prompt you set

函数

sass的函数主要包括

  • 字符串函数
  • 数字函数
  • 列表函数
  • 颜色函数
  • Introspection 函数
  • 三元函数
  • 自定义函数

下面主要介绍一下这些函数的方法。

字符串函数

1,unquote():

unquote() 函数主要是用来删除一个字符串中的引号,如果这个字符串没有带有引号,将返回原始的字符串。

2,quote():

quote() 函数刚好与 unquote() 函数功能相反,主要用来给字符串添加引号。如果字符串,自身带有引号会统一换成双引号 ""

3,To-upper-case():

To-upper-case() 函数将字符串小写字母转换成大写字母。

4,To-lower-case():

To-lower-case() 函数 与 To-upper-case() 刚好相反,将字符串转换成小写字母

.test1 {
    content:  unquote('Hello Sass!') ;//结果->content: Hello Sass!;
}
.test2 {
    content: quote(Hello Sass!);//结果->content: "Hello Sass!";
}
.test3 {
    content: to-upper-case("Hello Sass!");//结果->content: "HELLO SASS!" ;
}
.test4 {
    content:  to-lower-case("'Hello Sass!'");//结果->content: "hello sass!";
}

数字函数

1,percentage($value):将一个不带单位的数转换成百分比值;

2,round($value):将数值四舍五入,转换成一个最接近的整数

3,ceil($value):将大于自己的小数转换成下一位整数

4,floor($value):将一个数去除他的小数部分

5,abs($value):返回一个数的绝对值

6,min($numbers…):找出几个数值之间的最小值

7,max($numbers…):找出几个数值之间的最大值

8,random(): 获取随机数

.div1{
    width : percentage(5px / 10px) //20%
}
.div2{
    width : round(5.4px) //5px
}
.div3{
    width : ceil(7.1px) //8px
}
.div4{
    width : floor(9.9px) //9px
}
.div5{
    width : abs(-10px) //10px
}
.div6{
    width : min(5px ,10px) //5px
}
.div7{
    width : max(5px , 10px) //10px
}
.div8{
    width : random()px //鬼才知道的随机数
}

列表函数

length($list):返回一个列表的长度值;

nth($list, $n):返回一个列表中指定的某个标签

 join($list1, $list2, [$separator]):将两个列给连接在一起,变成一个列表

append($list1, $val, [$separator]):将某个值放在列表的最后

zip($lists…):将几个列表结合成一个多维的列表

index($list, $value):返回一个值在列表中的位置值。

 

length(10px) //1
length(10px 20px (border 1px solid) 2em) //4
length(border 1px solid) //3

nth(10px 20px 30px,1) //10px
nth((Helvetica,Arial,sans-serif),2) //"Arial"
nth((1px solid red) border-top green,1) //(1px "solid" #ff0000)

join(10px 20px, 30px 40px) //(10px 20px 30px 40px)
join((blue,red),(#abc,#def)) //(#0000ff, #ff0000, #aabbcc, #ddeeff)
join((blue red), join((#abc #def),(#dee #eff))) //(#0000ff #ff0000 #aabbcc #ddeeff #ddeeee #eeffff)

append(10px 20px ,30px) //(10px 20px 30px)

zip(1px 2px 3px,solid dashed dotted,green blue red) //((1px "solid" #008000), (2px "dashed" #0000ff), (3px "dotted" #ff0000))

index(1px solid red, solid) //2
需要注意的是join() 只能将两个列表连接成一个列表,如果直接连接两个以上的列表将会报错,但很多时候不只碰到两个列表连接成一个列表,这个时候就需要将多个 join() 函数合并在一起使用。在使用zip()函数时,每个单一的列表个数值必须是相同的。

Introspection函数

Introspection 函数包括了几个判断型函数:

  • type-of($value):返回一个值的类型
  • unit($number):返回一个值的单位
  • unitless($number):判断一个值是否带有单位
  • comparable($number-1, $number-2):判断两个值是否可以做加、减和合并
type-of(100) //"number"
type-of(100px) //"number"
type-of("asdf") //"string"
type-of(asdf) //"string"
type-of(true) //"bool"
type-of(#fff) //"color"

unit(100) //""
unit(100px) //"px"
unit(20%) //"%"
unit(10px * 3em) //"em*px"
unit(10px * 2em / 3cm / 1rem) //"em/rem"

unitless(100) //true
unitless(100px) //false
unitless(100em) //false
unitless(1 /2 + 2 ) //true
unitless(1px /2 + 2 ) //false

comparable(2px,1%) //false
comparable(2px,1em) //false
comparable(2px,1cm) //true
但加、减碰到不同单位时,unit() 函数将会报错,除 px 与 cm、mm 运算之外,unitless()有单位时返回false。

Miscellaneous函数

在这里把 Miscellaneous 函数称为三元条件函数,主要因为他和 JavaScript 中的三元判断非常的相似。他有两个值,当条件成立返回一种值,当条件不成立时返回另一种值:

if(true,1px,2px) //1px
if(false,1px,2px) //2px

Map

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

{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}

Sass Maps的函数

要在 Sass 中获取变量,或者对 map 做更多有意义的操作,我们必须借助于 map 的函数功能。在 Sass 中 map 自身带了七个函数:

  • map-get($map,$key):根据给定的 key 值,返回 map 中相关的值。
  • map-merge($map1,$map2):将两个 map 合并成一个新的 map。
  • map-remove($map,$key):从 map 中删除一个 key,返回一个新 map。
  • map-keys($map):返回 map 中所有的 key。
  • map-values($map):返回 map 中所有的 value。
  • map-has-key($map,$key):根据给定的 key 值判断 map 是否有对应的 value 值,如果有返回 true,否则返回 false。
  • keywords($args):返回一个函数的参数,这个参数可以动态的设置 key 和 value。

RGB颜色函数-RGB()颜色函数

在 Sass 的官方文档中,列出了 Sass 的颜色函数清单,从大的方面主要分为 RGB , HSL 和 Opacity 三大函数,当然其还包括一些其他的颜色函数,比如说 adjust-color 和 change-color 等。

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

  • rgb($red,$green,$blue):根据红、绿、蓝三个值创建一个颜色;
  • rgba($red,$green,$blue,$alpha):根据红、绿、蓝和透明度值创建一个颜色;
  • red($color):从一个颜色中获取其中红色值;
  • green($color):从一个颜色中获取其中绿色值;
  • blue($color):从一个颜色中获取其中蓝色值;
  • mix($color-1,$color-2,[$weight]):把两种颜色混合在一起。

HSL函数简介

在 Sass 中提供了一系列有关于 HSL 的颜色函数,以供大家使用,其中常用的有 saturation、lightness、adjust-hue、lighten、darken 等等。

  • 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):通过改变颜色的亮度值,让颜色变亮,创建一个新的颜色;
  • darken($color,$amount):通过改变颜色的亮度值,让颜色变暗,创建一个新的颜色;
  • saturate($color,$amount):通过改变颜色的饱和度值,让颜色更饱和,从而创建一个新的颜色
  • desaturate($color,$amount):通过改变颜色的饱和度值,让颜色更少的饱和,从而创建出一个新的颜色;
  • grayscale($color):将一个颜色变成灰色,相当于desaturate($color,100%);
  • complement($color):返回一个补充色,相当于adjust-hue($color,180deg);
  • invert($color):反回一个反相色,红、绿、蓝色值倒过来,而透明度不变。
hsl(200,30%,60%) //通过h200,s30%,l60%创建一个颜色 #7aa3b8
hsla(200,30%,60%,.8)//通过h200,s30%,l60%,a80%创建一个颜色 rgba(122, 163, 184, 0.8)
hue(#7ab)//得到#7ab颜色的色相值 195deg
saturation(#7ab)//得到#7ab颜色的饱和度值 33.33333%
lightness(#7ab)//得到#7ab颜色的亮度值 60%
adjust-hue(#f36,150deg) //改变#f36颜色的色相值为150deg #33ff66
lighten(#f36,50%) //把#f36颜色亮度提高50% #ffffff
darken(#f36,50%) //把#f36颜色亮度降低50% #33000d
saturate(#f36,50%) //把#f36颜色饱和度提高50% #ff3366
desaturate(#f36,50%) //把#f36颜色饱和度降低50% #cc667f
grayscale(#f36) //把#f36颜色变成灰色 #999999
complement(#f36) //#33ffcc
invert(#f36) //#00cc99

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):使颜色更加透明。

自定义函数简介

上面的一些函数可以说比较鸡肋或者话说在平时可能我们用不到,那么除了使用@mixin来进行一些操作以外,自定义函数是一个很好的选择,并且在做插件时是十分有用的。

$oneWidth: 10px;  
$twoWidth: 40px;  
  
@function widthFn($n) {  
  @return $n * $twoWidth + ($n - 1) * $oneWidth;  
}  
  
.leng {   
    width: widthFn(5);  
}  

 

其实市场上有一些比较好的sass库。这里推荐一下一个sass基础库Sandal以及基于Sandal(基础sass库)扩展的移动端UI库sheral

sandal取其“檀香”之意,针对移动端站点为前端人员提供了一些基础的重置,常用的mixin,如flex布局,等分,水平垂直居中,常用图标等,基于它你可以扩展出更多你需要的UI组件,sheral就是基于sandal的移动端UI库。

_function.scss集成了所有的基础功能,并且不输出任何样式,而_core.scss则在function的基础上加入了重置样式,ext文件夹则包含了四个扩展文件,可根据个人需要自由导入,具体介绍及使用请参考sandal 文档。

如何使用

sandal,分核心文件和扩展文件两种。其中核心文件包括重置样式,@mixin%等方便调用;而扩展文件则提供基础原子类class,图标,网格系统。

核心文件提供两个集合文件以供调用,分别为_function.scss, _core.scss。两者的区别为function仅提供功能,而core除了提供function的功能,还会会生成一份重置样式

扩展文件有四个,分别为_icons.scss_helper.scss_grid.scss_page-slide.scss可根据需要调用

 
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn