Front-end architect technology Sass

1 CSS Disadvantages

CSS is just a markup language, not a programming language, so variables cannot be customized or referenced. CSS mainly has the following disadvantages.

  • CSS is a non-procedural language and has no concepts such as variables, functions, and SCOPE (scope).
  • CSS requires writing a lot of seemingly illogical code, and the code redundancy is relatively high.
  • CSS doesn't have very good computing power.
  • It is inconvenient to maintain and expand, and is not conducive to reuse.

2 What is Sass

In order to solve the problems of CSS in the actual development process, we can use Sass (CSS preprocessor) to implement the page style.

  • Sass is a mature, stable, and powerful professional-grade CSS extension language.
  • It is an auxiliary tool for enhancing CSS.
  • On the basis of CSS syntax, advanced functions such as variables, nestedrules, mixins, and inline imports are added to make CSS more powerful and elegant.
  • Using Sass and Sass style libraries (such as Compass) helps to better organize and manage style files and develop projects more efficiently.
  • Sass is fully compatible with all versions of CSS.

The bottom line is: write less code and implement more styles.

3 Sass compilation

  • Sass online compilation tool Use tools to compile

  • VScode downloads and installs the Easy Sass plug-in for automatic compilation

  • VScode downloads and installs the Live Sass Compilerv plug-in for automatic compilation

// Live Sass 配置
"liveSassCompile.settings.generateMap": false,
"liveSassCompile.settings.autoprefix": [
    "> 1%",
    "last 2 versions"
],
"liveSassCompile.settings.excludeList": [
    "**",
    "**/node_modules/**",
    ".vscode/**"
],
"liveSassCompile.settings.formats": [
    {
    
    
        "format": "compressed",
        // "format": "expanded",
        "extensionName": ".min.css",
        "savePath": "~/../css/"
    }
]

4 Basic usage of Sass

4.1 Sass syntax format

  • One is the earliest Sass syntax format, called Indented Sass, often referred to as "Sass", which is a simplified format. This format has ".sass" as the extension. (no longer recommended)
  • Another syntax format is SCSS (SassyCSS). This format is only expanded on the basis of CSS3 syntax. All CSS3 syntax is common in SCSS, while adding Sass features. This format has ".scss" as the extension. (currently in use)

4.2 Sass variables

Sass uses the "$" symbol to identify variables such as $highlight-color and $sidebar-width.

Declaring Sass variables is similar to declaring CSS properties.

$color: #F90;

Any assignment that can be used as a CSS property value can be used as a Sass variable value, even multiple property values ​​separated by spaces or commas.

$basic-border: 1px solid black;
$plain-font: "Myriad Pro", "Myriad", "Helvetica", "Neue", "Helvetica";

After the variable definition is completed, the variable is not yet effective unless the variable is referenced.

Variables can be used wherever standard values ​​for CSS properties (such as 1px or bold) can exist.

When CSS is generated, variables are replaced by their values. Later, if you need a different value, you only need to change the value of this variable, and the values ​​generated everywhere that reference this variable will change accordingly.

$color: #F90;
.selected {
  border: 1px solid $color;
}

Special variables: If the variable needs to be embedded in a string, it must be written in #{}.

$side: left;
.rounded {
    border-#{$side}-radius: 5px;
}

4.3 Sass operations

Sass supports operations such as addition (+), subtraction (-), multiplication (*), division (/) and remainder (%) of numbers. If necessary, it will convert values ​​between different units. For example, 1in + 8pt is converted to 1.111in (the full name of pt is point, which is a natural unit of length, 1in=72pt. According to this formula, the converted result of 1in+8pt is 1.111in).

// 编译前
p {
    width: 1in + 8pt;
}
// 编译后
p {
    width: 1.111in; 
}

The "/" symbol is usually used to separate numbers in CSS, and in Sass, "/" is also given the function of division operation, but the two do not conflict.

In other words, if "/" separates two numbers in Sass, it will have the same effect in the compiled CSS file.

// 编译前
p {
    font: 10px/8px;
    $width: 1000px;
    width: $width/2;
    height: (500px/2); 
    margin-left: 5px + 8px/2px; 
}
// 编译后
p {
    font: 10px/8px;
    width: 500px;
    height: 250px;
    margin-left: 9px; 
}

When compiling code that uses the "/" operator, the compiled result of font remains unchanged because it is not wrapped in parentheses.

If you need to use a variable and at the same time ensure that the "/" symbol is not divided but is fully compiled into the CSS file, you only need to wrap the variable with a #{} interpolation statement.

p {
    $font-size: 12px;
    $line-height: 30px;
    font: #{$font-size}/#{$line-height};
}
  • Normal values ​​are operated with "/" and need to be wrapped in parentheses.
  • The variable value does not need to be operated with "/", and the variable needs to be wrapped with the #{} interpolation statement.

4.4 Sass Nesting

Sass provides a more powerful tool based on variables, namely rule nesting.

Sass variables are only more powerful when used together with rule nesting.

When writing code using CSS, we know that repeatedly writing selectors is very cumbersome.

For example, when you want to write a large series of styles that point to the same block of the page, you often need to write the same ID or class name over and over again.

#content article h1 {
    
     color: #333 }
#content article p {
    
     margin-bottom: 1.4em }
#content aside {
    
     background-color: #eee }

.box article h1 {
    
     color: #333 }
.box article p {
    
     margin-bottom: 1.4em }
.box aside {
    
     background-color: #eee }

Sass will automatically handle these nested rules when compiling and outputting CSS, avoiding duplication of code and making the style more readable. Sass can be implemented by just writing it once.

#content {
    article {
        h1 { color: #333 }
        p { margin-bottom: 1.4em }
    }
    aside { background-color: #eee }
}
.box {
    article {
        h1 { color: #333 }
        p { margin-bottom: 1.4em }
    }
    aside { background-color: #eee }
}

Properties can also be nested, such as the border-color property, which can be written as

// 编译前
.box {
    border: {
        color: red;
    }
}
// 编译后
.box {
    border-color: red;
}

Note: Nested attributes (border) must be followed by a colon.

Within nested code blocks, you can use & to refer to parent elements. For example: hover pseudo-class can be written as

// 编译前
.box {
    &:hover { color: red; }
}
// 编译后
.box:hover {
    color: red;
}

4.4 Sass comments

Sass has two comment styles

  • Single-line comments // 注释are only retained in the Sass source file, not in the compiled file.
  • Standard CSS comments /* 注释 */will be retained in the compiled file and deleted when compressed.
    • Add an exclamation mark after the standard comment /*! 重要注释 */ to indicate an important comment. The compression mode will also retain comments for copyright statements, etc.

5 Code reuse

5.1 Sass inheritance

In Sass, inheritance allows one selector to inherit all the styles of another selector. Inheritance uses the @extend command.

// 编译前
.alert{
    padding: 15px;
}

.alert a{
    text-decoration: none;
}

.alert-info{
    @extend .alert;
    background-color: lightblue;
}
// 编译后
.alert, .alert-info {
  padding: 15px;
}

.alert a, .alert-info a {
  text-decoration: none;
}

.alert-info {
  background-color: lightblue;
}

Use the placeholder selector % . Starting from Sass 3.2.0, you can define the placeholder selector %. The advantage of this is that there will be no redundant CSS files without calling it.

// 编译前
%h1 {
    font-size:20px;
}
div {
    @extend %h1;
    color:red;
}
// 编译后
div {
    font-size:20px;
    color:red;
}

5.2 Mixin

Mixins are chunks of code that can be reused.

  • Use the @mixin command to define a code block.
  • Use the @include command to call this mixin.
@mixin alert {
    color:#ccc;
    background-color:red;
}
div {
    @include alert;
}

The power of Mxin is that you can specify parameters and default values. When using it, add parameters as needed.

@mixin alert($color:red) {
    color:#ccc;
    background-color:$color;
}
div {
    @include alert(blue);
}

You can use Mixin to generate browser prefixes.

// 设置关键帧
@mixin keyframes($name) {
    @-webkit-keyframes #{$name} {
        @content;
    }
    @-moz-keyframes #{$name} {
        @content;
    }
    @-o-keyframes #{$name} {
        @content;
    }
    @keyframes #{$name} {
        @content;
    }
}
// 引入
@include keyframes(scale) {
    100% {
        transform: scale(0.8);
    }
}
// css编译后
@-webkit-keyframes scale {
    100% {
        transform: scale(0.8);
    }
}
@-moz-keyframes scale {
    100% {
        transform: scale(0.8);
    }
}
@-o-keyframes scale {
    100% {
        transform: scale(0.8);
    }
}
@keyframes scale {
    100% {
        transform: scale(0.8);
    }
}
@mixin rounded($attr, $value) {
    #{$attr}: $value;
    -moz-#{$attr}: $value;
    -webkit-#{$attr}: $value;
}
#navbar li {
    @include rounded(border-radius, 8px);
}

5.3 Color function

Sass provides some built-in color functions for generating a series of colors.

lighten(#cc3, 10%) // #d6d65c
darken(#cc3, 10%) // #a3a329
grayscale(#cc3) // #808080
complement(#cc3) // #33c

5.4 Inserting files

Use the @import command to introduce external files. After importing, you can use variables in the external files, etc.

@import "base.scss";

If a file is inserted .css, it is equivalent to the CSS import command.

@import "base.css";

6 Advanced Usage

6.1 Conditional statements

@if can be used for judgment, and the matching @else command

// Sass样式
$type: monster;
div {
    @if $type == ocean {
        color: blue;
    } @else if $type == matador {
        color: red;
    } @else if $type == monster {
        color: green;
    } @else {
        color: black;
    }
}
// css编译后样式
div {
    color: green;
}

**Trinocular judgment:** The syntax is if($condition, $if_true, $if_false)

The three parameters respectively represent: condition, value when the condition is true, and value when the condition is false.

if(true, 1px, 2px) => 1px
if(false, 1px, 2px) => 2px

$box: red;
$fontSize: if($box==red, 16px, 14px);
.box {
    font-size: $fontSize;
}

6.2 Loop statements

The for loop has two forms, namely:

  • @for $var from <start> through <end>

  • @for $var from <start> to <end>

$var represents a variable, start represents the start value, and end represents the end value. The difference between the two forms is that through includes the end value, and to does not include the end value.

@for $i from 1 to 10 {
    .border-#{$i} {
        border: #{$i}px solid blue;
    }
}

while loop

$i: 6;
@while $i > 0 {
    .item-#{$i} {
        width: 2em * $i;
    }
    $i: $i - 2;
}

each command is similar to for

  • The syntax is @each $var in <list or map>.

  • where $var represents the variable

@each $member in a, b, c, d {
    .#{$member} {
        background-image: url("/image/#{$member}.jpg");
    }
}

6.3 Custom functions

Sass allows users to write their own functions, starting with @function and returning a value with @return.

// 常规用法
@function double($n) {
    @return $n * 2;
}
#sidebar {
    width: double(5px);
}

// 常用用法
$fontSize: 100px;
@function pxTorem($px) {
    @return $px / $fontSize * 1rem;
}
div {
    font-size: pxTorem(24px);
}
// css编译后样式
div {
    font-size: .24rem;
}

7 Practice Assignments

  • Optimize mobile style sheets using Sass syntax

Guess you like

Origin blog.csdn.net/zhangchen124/article/details/133276966