search
HomeWeb Front-endCSS TutorialHow to use preprocessor Sass

This time I will show you how to use the preprocessor Sass, and what are the precautions for using the preprocessor Sass. The following is a practical case, let's take a look.

Sass is an auxiliary tool that enhances CSS. It adds advanced functions such as variables, nested rules, mixins, and inline imports based on CSS syntax. , these extensions make CSS more powerful and elegant. Using Sass and Sass style libraries (such as Compass) can help you better organize and manage style files and develop projects more efficiently.

1. Features

  1. Fully compatible with CSS3

  2. Add variables and Functions such as nesting and mixins

  3. Perform operations on color values ​​and attribute values ​​through functions

  4. Provides control instructions ( control directives) and other advanced functions

  5. Customized output format

File suffix name:sass has two suffix names One file has the suffix name sass and does not use braces and semicolons; the other is the scss file we use here, which is similar to the css file format we usually write, using braces and semicolons. All sass files mentioned in this tutorial refer to files with the suffix scss. It is also recommended to use files with the suffix scss to avoid errors due to the strict format requirements of the sass suffix.

//文件后缀名为sass的语法
body
  background: #eee
  font-size:12px
p
  background: #0982c1
//文件后缀名为scss的语法  
body {
  background: #eee;
  font-size:12px;
}
p{
  background: #0982c1;
}

2. Syntax comparison between Sass and Less

2.1 The difference between Sass and Less

  1. Compilation environments are different - Sass is compiled based on server-side environments such as Ruby, and Less can support both server-side compilation and client-side (browser environment) compilation

  2. Variable symbols are different ——Sass uses the $ symbol to declare variables, and Less uses the @ symbol to declare variables.

  3. has different support for conditional statements. ——Sass supports complex conditional statements (similar to if..else. .), Less only supports simple conditional statements (similar to if()..)

  4. Scope - Sass locally modifying variables can affect global variables, while Less will only locally modify variables Scope takes effect.

  5. The ways to reference external CSS files are different - Sass can ignore the suffix when importing .sass or .scss files by default, while Less needs to control how the imported files are processed through keyword configuration.

2.2 Similarities between Sass and Less

  1. Mixins - similar to functions or macros, and Parameters can be passed;

  2. Nesting rules - nesting classes within classes, thereby reducing repeated code;

  3. Operations - in CSS Use addition, subtraction, multiplication and division to calculate various numerical values ​​and strings, etc.;

  4. Color function - you can edit colors through built-in functions;

  5. Namespace (namespace)——Group styles so that they can be called;

3. Introduction to the main functions of Sass syntax

3.1 CSS functions Extension

Nesting rules

Sass allows one set of CSS styles to be nested within another set of styles. The inner style will nest its outer style. The selector acts as a parent selector, and the nesting function avoids repeatedly entering the parent selector and makes complex CSS structures easier to manage, for example:

//sass style or less style
#main p {
  color: #00ff00;
  width: 97%;
  .redbox {
    background-color: #ff0000;
    color: #000000;
  }
}
//css style
#main p {
color: #00ff00;
width: 97%; }
#main p .redbox {
  background-color: #ff0000;
  color: #000000; }

Parent Selector&

When nesting CSS rules, sometimes it is necessary to directly use the nested outer parent selector. For example, when setting a hover style for an element, or when the body element has a certain classname, you can use & Represents the parent selector outside the nested rule.

//sass style or less style
a {
  font-weight: bold;
  text-decoration: none;
  &:hover { text-decoration: underline; }
  body.firefox & { font-weight: normal; }
}
//css style
a {
font-weight: bold;
text-decoration: none; }
a:hover {
  text-decoration: underline; }
body.firefox a {
  font-weight: normal; }

Attribute nesting

Some CSS properties follow the same namespace (namespace), such as font-family, font-size, font-weight all use font as The namespace of the attribute. In order to facilitate the management of such attributes and avoid repeated input, Sass allows attributes to be nested in namespaces, for example:

//sass style
.funky {
  font: {
    family: fantasy;
    size: 30em;
    weight: bold;
  }
}
//css style
.funky {
  font-family: fantasy;
  font-size: 30em;
  font-weight: bold; }

Namespaces can also contain their own attribute values, for example:

//sass style
.funky {
  font: 20px/24px {
    family: fantasy;
    weight: bold;
  }
}
//css style
.funky {
  font: 20px/24px;
    font-family: fantasy;
    font-weight: bold; }

3.2Import

sass的导入(@import)规则和CSS的有所不同,编译时会将@import的scss文件合并进来只生成一个CSS文件。但是如果你在sass文件中导入css文件如 @import ‘reset.css’,那效果跟普通CSS导入样式文件一样,导入的css文件不会合并到编译后的文件中,而是以 @import 方式存在。

所有的sass导入文件都可以忽略后缀名.scss。一般来说基础的文件命名方法以_开头,如_mixin.scss。这种文件在导入的时候可以不写下划线,可写成@import “mixin”。

less的导入(@import)语法:@import (keyword) “filename”;

多个关键字 @import 是允许的,你必须使用逗号分隔关键字:example: @import (optional, reference) “foo.less”;

  1. reference: 使用该less文件但是不输出它

  2. inline: 包括在源文件中输出,但是不作处理

  3. less: 将该文件视为less文件,无论其扩展名为什么

  4. css: 将文件视为css文件,无论扩展名为什么

  5. once: 该文件仅可导入一次 (默认)

  6. multiple: 该文件可以多次导入

  7. optional: 当没有发现文件时仍然编译

导入文件代码示例:

/*被导入sass文件a.scss,less文件a.less:*/
//a.scss or a.less
//-------------------------------
body {
  background: #eee;
}
/*需要导入样式的sass文件b.scss,less文件b.less:*/
@import "reset.css";
@import "a";
p{
  background: #0982c1;
}   
/*转译出来的b.css样式:*/
@import "reset.css";
body {
  background: #eee;
}
p{
  background: #0982c1;
}

根据上面的代码可以看出,b.scss编译后,reset.css继续保持import的方式,而a.scss则被整合进来了。同理,less中也是这样处理的。

3.3 注释 /* */ 与 //

Sass 支持标准的 CSS 多行注释 /* */,以及单行注释 //,前者会被完整输出到编译后的 CSS 文件中,而后者则不会。Less中不用担心这一点,Less中多行注释 /* */,以及单行注释 //都可以随意使用,都会在编译过程中被保留。例如:

//sass style
/* This comment is
 * several lines long.
 * since it uses the CSS comment syntax,
 * it will appear in the CSS output. */
body { color: black; }
// These comments are only one line long each.
// They won't appear in the CSS output,
// since they use the single-line comment syntax.
a { color: green; }
//css style
/* This comment is
 * several lines long.
 * since it uses the CSS comment syntax,
 * it will appear in the CSS output. */
body {
  color: black; }
a {
  color: green; }

3.4 SassScript

变量 $

Sass的变量必须是$开头,后面紧跟变量名,如果值后面加上!default则表示默认值。Less的变量与Sass类似,只是使用符号不同,Less中采用的是@

//sass style
//-------------------------------
$fontSize: 12px;
body{
    font-size:$fontSize;
}  
//less style
//-------------------------------
@fontSize: 12px;
body{
    font-size:@fontSize;
}
//css style
//-------------------------------
body{
    font-size:12px;
}

变量默认值

sass的默认变量一般是用来设置默认值,然后根据需求来覆盖的,覆盖的方式也很简单,只需要在使用默认变量之前重新声明下变量即可;默认变量的价值在进行组件化开发的时候会非常有用。

//sass style
//-------------------------------
$baseLineHeight:  1.5 !default;
body{
    line-height: $baseLineHeight; 
}
//css style
//-------------------------------
body{
    line-height:1.5;
}
/*覆盖默认值*/
//sass style
//-------------------------------
$baseLineHeight:  2;
$baseLineHeight:  1.5 !default;
body{
    line-height: $baseLineHeight; 
}
//css style
//-------------------------------
body{
    line-height:2;
}

变量 #{} 的使用形式

一般我们定义的变量都为属性值,可直接使用,但是如果变量作为属性或在某些特殊情况下等则必须要以#{$variables}形式使用。

//sass style
//-------------------------------
$borderDirection:    top !default; 
$baseFontSize:       12px !default;
$baseLineHeight:     1.5 !default;
//应用于class和属性
.border-#{$borderDirection}{
  border-#{$borderDirection}:1px solid #ccc;
}
//应用于复杂的属性值
body{
    font:#{$baseFontSize}/#{$baseLineHeight};
}
//css style
//-------------------------------
.border-top{
  border-top:1px solid #ccc;
}
body {
  font: 12px/1.5;
}

多值变量 list

简单来说list类型有点像js中的数组。list数据可通过空格,逗号或小括号分隔多个值,可用nth($var,$index)取值。

关于list数据操作还有很多其他函数如length($list),join($list1,$list2,[$separator]),append($list,$value,[$separator])等

定义:

//一维数据
$px: 5px 10px 20px 30px;
//二维数据,相当于js中的二维数组
$px: 5px 10px, 20px 30px;
$px: (5px 10px) (20px 30px);

使用方法:

//sass style
//-------------------------------
$linkColor:  #08c #333 !default;//第一个值为默认值,第二个鼠标滑过值
a{
  color:nth($linkColor,1);
  &:hover{
    color:nth($linkColor,2);
  }
}
//css style
//-------------------------------
a{
  color:#08c;
}
a:hover{
  color:#333;
}

多值变量 map

简单来说map类型有点像es6语法中的map数据结构。map数据以key和value成对出现,其中value又可以是list。

格式为:$map: (key1: value1, key2: value2, key3: value3);可通过map-get($map,$key)取值。关于map数据还有很多其他函数如map-merge($map1,$map2),map-keys($map),map-values($map)等

定义:

$heading: (h1: 2em, h2: 1.5em, h3: 1.2em);

使用方法:

//sass style
//-------------------------------
$headings: (h1: 2em, h2: 1.5em, h3: 1.2em);
@each $header, $size in $headings {
  #{$header} {
    font-size: $size;
  }
}
//css style
//-------------------------------
h1 {
  font-size: 2em; 
}
h2 {
  font-size: 1.5em; 
}
h3 {
  font-size: 1.2em; 
}

变量作用域

Sass和Less中的变量作用域分别类似与javascript中的两种变量申明方式,下面一段代码可以对比出变量声明时的不同处理方式。

Sass中的变量赋值直接修改全局变量,Less中的变量赋值可只在局部生效。

//Sass style
$color:red; 
p{ 
  $color:blue; 
  color:$color;//blue 
} 
a{ 
  color:$color;//blue 
}
//Less style
@color:red; 
p{ 
  @color:blue; 
  color:@color;//blue 
} 
a{ 
  color:@color;//red 
}

3.5 混合(mixin)

sass中使用@mixin声明混合,可以传递参数,也可以给参数设置默认值。声明的@mixin通过@include来调用;在less中只需要将定义好的class用类似函数的方式直接引用。

无参数 mixin

//sass style
@mixin center-block {
    margin-left:auto;
    margin-right:auto;
}
.demo{
    @include center-block;
}
//less style
.center-block {
    margin-left:auto;
    margin-right:auto;
}
.demo{
    .center-block;
}
//css style
.demo{
    margin-left:auto;
    margin-right:auto;
}

有参数 mixin

//sass style
@mixin opacity($opacity:50) {
  opacity: $opacity / 100;
  filter: alpha(opacity=$opacity);
}
.opacity-80{
  @include opacity(80); //传递参数
}
//less style
.opacity(@opacity:50) {
  opacity: @opacity / 100;
  filter: alpha(opacity=@opacity);
}
.opacity-80{
  .opacity(80); //传递参数
}
//css style
.opacity-80{
  opacity: .8;
  filter: alpha(opacity=80);
}

多个参数 mixin

Sass调用时可直接传入值,如@include传入参数的个数小于@mixin定义参数的个数,则按照顺序表示,后面不足的使用默认值,如不足的没有默认值则报错。除此之外还可以选择性的传入参数,使用参数名与值同时传入;Less中使用方法类似。

//sass style   
@mixin horizontal-line($border:1px dashed #ccc, $padding:10px){
    border-bottom:$border;
    padding-top:$padding;
    padding-bottom:$padding;  
}
.imgtext-h li{
    @include horizontal-line(1px solid #ccc);
}
//less style
.horizontal-line(@border:1px dashed #ccc, @padding:10px){
    border-bottom:@border;
    padding-top:@padding;
    padding-bottom:@padding;  
}
.imgtext-h li{
    .horizontal-line(1px solid #ccc);
}
//css style
.imgtext-h li {
    border-bottom: 1px solid #cccccc;
    padding-top: 10px;
    padding-bottom: 10px;
}

多组值参数 mixin

Sass中如果一个参数可以有多组值,如box-shadow、transition等,那么参数则需要在变量后加三个点表示,如$variables…;Less表示不定参数时可以直接使用 … 表示,并用@arguments表示所有参数

//sass style   
//box-shadow可以有多组值,所以在变量参数后面添加...
@mixin box-shadow($shadow...) {
  -webkit-box-shadow:$shadow;
  box-shadow:$shadow;
}
.box{
  border:1px solid #ccc;
  @include box-shadow(0 2px 2px rgba(0,0,0,.3),0 3px 3px rgba(0,0,0,.3),0 4px 4px rgba(0,0,0,.3));
}
//less style
.box-shadow(...) {
  -webkit-box-shadow:@arguments;
  box-shadow:@arguments;
}
.box{
  border:1px solid #ccc;
  .box-shadow(0 2px 2px rgba(0,0,0,.3),0 3px 3px rgba(0,0,0,.3),0 4px 4px rgba(0,0,0,.3));
}
//css style
.box{
  border:1px solid #ccc;
  -webkit-box-shadow:0 2px 2px rgba(0,0,0,.3),0 3px 3px rgba(0,0,0,.3),0 4px 4px rgba(0,0,0,.3);
  box-shadow:0 2px 2px rgba(0,0,0,.3),0 3px 3px rgba(0,0,0,.3),0 4px 4px rgba(0,0,0,.3);
}

3.6 运算

sass具有运算的特性,可以对数值型的Value(如:数字、颜色、变量、字符串等)进行加减乘除四则运算。请注意运算符前后请留一个空格,不然会出错。

//计算数值、变量
$baseFontSize:          14px !default;
$baseLineHeight:        2 !default;
$baseGap:               $baseFontSize * $baseLineHeight !default; // => 28px
$halfBaseGap:           $baseGap / 4  !default; // => 7px
$samllFontSize:         $baseFontSize - 2px  !default; // => 12px
$_columns:              12 !default;  
$_column-width:         60px !default;  
$_gutter:               20px !default;     
$_gridsystem-width:     $_columns * ($_column-width + $_gutter); // => 960px
//计算颜色
p {
  color: #010203 + #040506; // => #050709
}
//计算字符串
p:before {
  content: "Foo " + Bar; // => "Foo Bar"
  font-family: sans- + "serif"; // => sans-serif
}

3.7 控制指令

SassScript 提供了一些基础的控制指令,比如在满足一定条件时引用样式,或者设定范围重复输出格式。控制指令是一种高级功能,日常编写过程中并不常用到,主要与混合指令 (mixin) 配合使用。

@if

//sass style
p {
  @if 1 + 1 == 2 { border: 1px solid; }
  @if 5 <p style="text-align: left;"><strong>@for</strong></p><p style="text-align: left;">@for 指令包含两种格式:@for $var from <start> through <end>,或者 @for $var from <start> to <end>,区别在于 through 与 to 的含义:当使用 through 时,条件范围包含 <start> 与 <end> 的值,而使用 to 时条件范围只包含 <start> 的值不包含 <end> 的值。另外,$var 可以是任何变量,比如 $i;<start> 和 <end> 必须是整数值。</end></start></end></start></end></start></end></start></end></start></p><pre class="brush:php;toolbar:false">//sass style
@for $i from 1 through 3 {
  .item-#{$i} { width: 2em * $i; }
}
//css style
.item-1 {
  width: 2em; }
.item-2 {
  width: 4em; }
.item-3 {
  width: 6em; }

@each

语法为:@each $var in 。其中$var表示变量,而list和map表示list类型数据和map类型数据。

单个字段list数据循环:

//sass style
$animal-list: puma, sea-slug, egret, salamander;
@each $animal in $animal-list {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
  }
}
//css style
.puma-icon {
  background-image: url('/images/puma.png'); 
}
.sea-slug-icon {
  background-image: url('/images/sea-slug.png'); 
}
.egret-icon {
  background-image: url('/images/egret.png'); 
}
.salamander-icon {
  background-image: url('/images/salamander.png'); 
}

多个字段list数据循环:

//sass style
//-------------------------------
$animal-data: (puma, black, default),(sea-slug, blue, pointer),(egret, white, move);
@each $animal, $color, $cursor in $animal-data {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
    border: 2px solid $color;
    cursor: $cursor;
  }
}
//css style
//-------------------------------
.puma-icon {
  background-image: url('/images/puma.png');
  border: 2px solid black;
  cursor: default; 
}
.sea-slug-icon {
  background-image: url('/images/sea-slug.png');
  border: 2px solid blue;
  cursor: pointer; 
}
.egret-icon {
  background-image: url('/images/egret.png');
  border: 2px solid white;
  cursor: move; 
}

多个字段map数据循环:

//sass style
//-------------------------------
$headings: (h1: 2em, h2: 1.5em, h3: 1.2em);
@each $header, $size in $headings {
  #{$header} {
    font-size: $size;
  }
}
//css style
//-------------------------------
h1 {
  font-size: 2em; 
}
h2 {
  font-size: 1.5em; 
}
h3 {
  font-size: 1.2em; 
}

@extend

@extend 的作用是将重复使用的样式 (.error) 延伸 (extend) 给需要包含这个样式的特殊样式(.seriousError),例子:

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

3.8 函数指令

Sass 支持自定义函数,并能在任何属性值或 Sass script 中使用:

//sass style
//-------------------------------
$grid-width: 40px;
$gutter-width: 10px;
@function grid-width($n) {
  @return $n * $grid-width + ($n - 1) * $gutter-width;
}
#sidebar { width: grid-width(5); }
//css style
//-------------------------------
#sidebar {
  width: 240px; }

与 mixin 相同,也可以传递若干个全局变量给函数作为参数。一个函数可以含有多条语句,需要调用 @return 输出结果。

Sass 函数允许使用关键词参数,上面的例子也可以写成:

//关键词参数调用形式
#sidebar { width: grid-width($n: 5); }

虽然不够简明,但是阅读起来会更方便。关键词参数给函数提供了更灵活的接口,以及容易调用的参数。关键词参数可以打乱顺序使用,如果使用默认值也可以省缺,另外,参数名被视为变量名,下划线、短横线可以互换使用。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

毛毛虫爬行动画怎样实现

重绘与重排如何使用

Canvas制作旋转太极的动画

The above is the detailed content of How to use preprocessor Sass. For more information, please follow other related articles on the PHP Chinese website!

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
css ul标签怎么去掉圆点css ul标签怎么去掉圆点Apr 25, 2022 pm 05:55 PM

在css中,可用list-style-type属性来去掉ul的圆点标记,语法为“ul{list-style-type:none}”;list-style-type属性可设置列表项标记的类型,当值为“none”可不定义标记,也可去除已有标记。

css与xml的区别是什么css与xml的区别是什么Apr 24, 2022 am 11:21 AM

区别是:css是层叠样式表单,是将样式信息与网页内容分离的一种标记语言,主要用来设计网页的样式,还可以对网页各元素进行格式化;xml是可扩展标记语言,是一种数据存储语言,用于使用简单的标记描述数据,将文档分成许多部件并对这些部件加以标识。

sass软件是什么意思sass软件是什么意思Aug 15, 2022 am 11:39 AM

sass全称“Software as a service”,意思为“软件即服务”;它是一种软件部署模式,第三方供应商在云基础设施上构建应用程序,并以订阅的形式,通过互联网向客户提供这些应用程序,不要求客户预先建设底层基础设施。这意味着软件可以在任何有互联网连接和网络浏览器的设备上访问,而不像传统软件那样只能在本地机器上安装。

css3怎么实现鼠标隐藏效果css3怎么实现鼠标隐藏效果Apr 27, 2022 pm 05:20 PM

在css中,可以利用cursor属性实现鼠标隐藏效果,该属性用于定义鼠标指针放在一个元素边界范围内时所用的光标形状,当属性值设置为none时,就可以实现鼠标隐藏效果,语法为“元素{cursor:none}”。

rtl在css是什么意思rtl在css是什么意思Apr 24, 2022 am 11:07 AM

在css中,rtl是“right-to-left”的缩写,是从右往左的意思,指的是内联内容从右往左依次排布,是direction属性的一个属性值;该属性规定了文本的方向和书写方向,语法为“元素{direction:rtl}”。

css怎么设置i不是斜体css怎么设置i不是斜体Apr 20, 2022 am 10:36 AM

在css中,可以利用“font-style”属性设置i元素不是斜体样式,该属性用于指定文本的字体样式,当属性值设置为“normal”时,会显示元素的标准字体样式,语法为“i元素{font-style:normal}”。

css怎么实现英文小写转为大写css怎么实现英文小写转为大写Apr 25, 2022 pm 06:35 PM

转换方法:1、给英文元素添加“text-transform: uppercase;”样式,可将所有的英文字母都变成大写;2、给英文元素添加“text-transform:capitalize;”样式,可将英文文本中每个单词的首字母变为大写。

怎么设置rotate在css3的旋转中心点怎么设置rotate在css3的旋转中心点Apr 24, 2022 am 10:50 AM

在css3中,可以用“transform-origin”属性设置rotate的旋转中心点,该属性可更改转换元素的位置,第一个参数设置x轴的旋转位置,第二个参数设置y轴旋转位置,语法为“transform-origin:x轴位置 y轴位置”。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool