Sass in action: more efficient CSS development

Table of contents

1. Preparations

1.1 Install Sass

1.2 Create HTML files and Sass files

2. Variables and Nesting

2.1 Variables

2.2 Nesting

3. mix

3.1 Defining a mix

3.2 Call mix

4. Inheritance

4.1 Define inheritance

4.2 Inheritance Considerations

5. Conditions and Loops

5.1 Conditional Statements

5.2 Loop Statements

6. Import and Modularization

6.1 Import files

6.2 Modularity

7. Nesting rules

8. Calculate

9. Notes

10. The level caused by nesting is too deep

11. Compile Sass

12. Summary


Sass (Syntactically Awesome Style Sheets) is a CSS preprocessor that extends the functionality of CSS and provides us with a more flexible and efficient way of CSS development. By using Sass, we can use variables, nesting, mixing and other functions to write more maintainable and reusable CSS code. This blog will introduce the basic usage of Sass, and demonstrate through examples how to apply Sass in projects to improve CSS development efficiency.

1. Preparations

Before we start, we need to install Sass and prepare an HTML file and Sass file for the example.

1.1 Install Sass

Sass can be installed via npm. Open the command line terminal and execute the following command to install Sass globally:

 
 
npm install -g sass

After the installation is complete, we can use commands on the command line sassto compile Sass files.

1.2 Create HTML files and Sass files

index.htmlCreate a file and a file in the project root directory styles.scssfor displaying and writing Sass code.

 
 
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <title>Sass实战</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <header>
    <h1>Sass实战</h1>
  </header>
  <section>
    <p class="primary-text">这是一个Sass实例。</p>
    <button class="primary-button">点击按钮</button>
  </section>
</body>
</html>
 
 
// styles.scss
$primary-color: #007bff;

header {
  background-color: $primary-color;
  color: white;
  text-align: center;
  padding: 20px;
}

section {
  padding: 20px;
  text-align: center;

  .primary-text {
    font-size: 18px;
    color: $primary-color;
  }

  .primary-button {
    background-color: $primary-color;
    color: white;
    border: none;
    padding: 10px 20px;
    cursor: pointer;
  }
}

In the above code, we defined a $primary-colorvariable to hold the theme color. We then used that variable in the style of the headerand element. sectionIn addition, we use nested syntax to nest .primary-textand .primary-buttonselectors within sectionselectors to make the style more clear and readable.

2. Variables and Nesting

Two of the most fundamental features of Sass are variables and nesting. By using variables, we can define and reuse some commonly used values ​​in CSS, making the code easier to maintain. And through nesting, we can nest child selectors in parent selectors, making the style hierarchy clearer.

2.1 Variables

In Sass, variables $begin with a symbol followed by a colon and semicolon between the variable name and value. For example, we can use variables to define theme colors and font sizes:

 
 
// 定义变量
$primary-color: #007bff;
$font-size: 16px;

// 使用变量
header {
  background-color: $primary-color;
  font-size: $font-size;
}

2.2 Nesting

By nesting, we can organize styles more clearly and reduce repetitive code. For example, we can nest .primary-textand .primary-buttonselectors inside sectionselectors:

 
 
section {
  padding: 20px;
  text-align: center;

  .primary-text {
    font-size: 18px;
    color: $primary-color;
  }

  .primary-button {
    background-color: $primary-color;
    color: white;
    border: none;
    padding: 10px 20px;
    cursor: pointer;
  }
}

Nesting can make the style hierarchy clearer, and it can also reduce the duplication of selectors.

3. mix

Sass provides a mix (Mixins) function for reusing a set of style rules. By defining a mixin, we can encapsulate a set of style rules into a reusable block of code and call it where needed.

3.1 Defining a mix

A mixin @mixinis defined using the keyword followed by the mixin name and a pair of curly braces. Inside the braces, we can write a set of style rules:

 
 
// 定义混合
@mixin rounded-corners {
  border-radius: 5px;
  -webkit-border-radius: 5px;
}

In the code above, we define a rounded-cornersmixin named , which contains border-radiusproperties and -webkit-border-radiusattributes.

3.2 Call mix

To use a mixin, we @includecall it with the keyword followed by the mixin name:

 
 
// 使用混合
button {
  @include rounded-corners;
  background-color: $primary-color;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}

In the above code, we have called mixins @includeusing keywords to apply properties to elements.rounded-cornersborder-radiusbutton

4. Inheritance

With the Extend function, we can inherit the style of one selector to another selector. Through inheritance, we can achieve style reuse and reduce code redundancy.

4.1 Define inheritance

To define inheritance, we use @extendthe keyword followed by the selector to inherit from:

 
 
// 定义继承
.button-base {
  background-color: $primary-color;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}

.primary-button {
  @extend .button-base;
}

.secondary-button {
  @extend .button-base;
  background-color: #6c757d;
}

In the above code, we first define a .button-baseselector called , which contains the basic style of the button. Then, we use @extendthe keyword to .primary-buttoninherit the style from the selector .button-base. At the same time, we can also .primary-buttonadjust the style, such as modifying the background color. Similarly, we can also let the .secondary-buttoninherited .button-basestyle, and modify the background color.

4.2 Inheritance Considerations

When using inheritance, you need to pay attention to the following points:

  • Avoid excessive inheritance: Excessive inheritance will cause the generated CSS rules to become complicated, affecting performance and maintainability.
  • Don't Inherit Generic Selectors: Avoid inheriting styles to selectors that are too generic, which can lead to undesired style pollution.

5. Conditions and Loops

Sass also supports conditional statements and loop statements, making style processing more flexible and efficient.

5.1 Conditional Statements

With conditional statements, we can decide whether to apply certain styles based on certain conditions. For example, we can set different styles according to the type of button:

 
 
// 条件语句
@mixin button-style($type) {
  @if $type == "primary" {
    background-color: $primary-color;
    color: white;
  } @else if $type == "secondary" {
    background-color: #6c757d;
    color: white;
  } @else {
    background-color: #f8f9fa;
    color: #343a40;
  }
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}

// 使用条件语句
button {
  @include button-style("primary");
}

a.button {
  @include button-style("secondary");
}

input.button {
  @include button-style("default");
}

In the code above, we define a button-stylemixin called , which takes one $typeparameter. Depending on $typethe value, we apply different styles. We then called this mixin in the button, a.buttonand selectors, passing in different parameters.input.button$type

5.2 Loop Statements

With looping statements, we can repeatedly apply a set of style rules in a style. For example, we can use a loop to generate styles for multiple buttons:

 
 
// 循环语句
@for $i from 1 through 5 {
  .button-#{$i} {
    font-size: 14px + $i * 2;
    padding: 5px + $i * 2;
  }
}

In the above code, we use @fora loop from 1 to 5 to generate 5 button styles. font-sizeThe sum of each button is incremented by the paddingvalue of .$i

6. Import and Modularization

Sass supports importing other Sass files, making the management of style files more flexible and modular. We can split the styles into multiple files and import these files in the main file.

6.1 Import files

Suppose we _variables.scssuse files for variables and _mixins.scssfiles for mixins, and then styles.scssimport these files in:

 
 
// _variables.scss
$primary-color: #007bff;
$font-size: 16px;

// _mixins.scss
@mixin rounded-corners {
  border-radius: 5px;
  -webkit-border-radius: 5px;
}

// styles.scss
@import "variables";
@import "mixins";

header {
  background-color: $primary-color;
  color: white;
  text-align: center;
  padding: 20px;
}

section {
  padding: 20px;
  text-align: center;

  .primary-text {
    font-size: 18px;
    color: $primary-color;
  }

  .primary-button {
    @include rounded-corners;
    background-color: $primary-color;
    color: white;
    border: none;
    padding: 10px 20px;
    cursor: pointer;
  }
}

With @importkeywords, we can import _variables.scssand _mixins.scssfiles into styles.scss. This way, we can styles.scssuse these variables and mixins directly in .

6.2 Modularity

By importing and modularizing, we can split styles into multiple files, making style files clearer and easier to maintain. For example, we could put the button styles in a separate file:

 
 
// _button.scss
@import "variables";
@import "mixins";

.button-base {
  background-color: $primary-color;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}

.primary-button {
  @extend .button-base;
}

.secondary-button {
  @extend .button-base;
  background-color: #6c757d;
}

Then styles.scssimport this file in:

 
 
// styles.scss
@import "variables";
@import "mixins";
@import "button";

header {
  background-color: $primary-color;
  color: white;
  text-align: center;
  padding: 20px;
}

section {
  padding: 20px;
  text-align: center;

  .primary-text {
    font-size: 18px;
    color: $primary-color;
  }
}

In this way, we can divide the style file into multiple small modules, making the style organization more clear and modular.

7. Nesting rules

In Sass, we can use symbols inside style rules &to refer to parent selectors. This nesting rule makes style writing more concise and flexible.

 
 
// 嵌套规则
.button {
  font-size: 16px;

  &:hover {
    color: $primary-color;
  }

  &::before {
    content: ">";
  }

  &.primary {
    background-color: $primary-color;
    color: white;
  }
}

In the code above, we use &the notation to refer to .buttonthe selectors, defining the &:hover, , &::beforeand &.primarystyle rules, respectively. This way, we can .buttoncentralize all the style rules related to .

8. Calculate

Sass also supports simple mathematical calculations, making style writing more flexible. We can perform operations such as addition, subtraction, multiplication, and division in styles.

 
 
// 计算
.container {
  width: 100%;
  padding: 20px;
}

.item {
  width: 50%;
  margin: 0 auto;
  padding: 10px;
}

.total {
  width: 100% - 40px;
  padding: 10px * 2;
}

In the code above, we did the subtraction in the style, calculated .totalwidth and padding.

9. Notes

Sass supports a variety of annotation methods, making style documentation clearer and easier to maintain.

 
 
// 单行注释
/* 多行注释 */

10. The level caused by nesting is too deep

When using the nesting function of Sass, you need to pay attention to avoid too deep nesting levels. Too deep nesting will make the generated CSS rules complex, affecting performance and maintainability. To maintain moderate nesting, avoid excessive nesting.

11. Compile Sass

After writing the Sass file, we need to compile the Sass code into CSS code, and then import the generated CSS file into HTML.

Open the command line terminal, enter the directory where the Sass file is stored, and execute the following command to compile the Sass file:

 
 
sass styles.scss styles.css

The above command will styles.scsscompile the file into styles.cssa file.

12. Summary

By using Sass, we can greatly improve the efficiency and maintainability of CSS development. The functions of Sass variables, nesting, mixing, inheritance, conditions, and loops allow us to write styles more flexibly, reduce code redundancy, and achieve modularization and reuse of styles. I hope this blog can provide you with some practical Sass tips and examples to help you develop CSS more efficiently in your projects.

Guess you like

Origin blog.csdn.net/m0_68036862/article/details/131955278