2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Table of contents
Comparison between scss and css
Distinguishing default variables
Distinguish between global variables and local variables
Nested parent selector references (&)
Advantages and applicable scenarios
Advantages and applicable scenarios
Using Conditional Statements in SCSS
Nesting of conditional statements
Custom functions and their use
SCSS (Sassy CSS) is a preprocessor language for CSS. It provides more functions and flexibility based on CSS, making the writing and management of style sheets more efficient and convenient.
Here are some advantages of SCSS:
In summary, SCSS not only retains all the functions of CSS, but also introduces advanced features such as variables, nesting, mixing, and importing. These features enable developers to write and manage style sheets more efficiently. It is one of the commonly used tools in modern front-end development.
grammar:
Readability and maintainability:
Function extension:
compatibility:
learning curve:
In summary, SCSS provides more tools and features to simplify the writing and maintenance of style sheets than ordinary CSS, and is especially suitable for the development of large and complex projects. However, for small projects or simple style requirements, ordinary CSS may be more direct and convenient.
Before learning scss, install two plug-ins in vscode to convert scss into ordinary CSS files for subsequent learning!
Search for sass in the plugin store, download the following two plugins and restart vscode!
Declaring variables in SCSS is very simple. You can use the $ symbol to define a variable.
Here is a simple example showing how to declare and use variables in SCSS:
- // 定义变量
- $primary-color: #3498db;
- $secondary-color: #2ecc71;
-
- // 使用变量
- body {
- background-color: $primary-color;
- }
-
- a {
- color: $secondary-color;
- }
In the example above, we define two variables, $primary-color and $secondary-color, to store the primary and secondary colors respectively. We can then use these variables in style rules to keep the colors consistent and easy to modify throughout the stylesheet.
When a SCSS file is compiled into a regular CSS file, all variables will be replaced with their corresponding values, so the final generated CSS file will not contain any variable declarations.
In SCSS, you can use default variables to ensure that a variable has a fallback value when it is not defined. This is particularly useful when dealing with theming or configuring styles.
Here is an example of how to declare and use a default variable:
- // 声明变量,并设置默认值
- $primary-color: #3498db !default;
- $secondary-color: #2ecc71 !default;
-
- // 使用变量
- body {
- background-color: $primary-color;
- }
-
- a {
- color: $secondary-color;
- }
In the example above, we have used the !default tag to define default values. This means that if $primary-color or $secondary-color are not defined elsewhere before the SCSS file is included, they will use the specified default values (#3498db and #2ecc71). If these variables have been defined before the file is included, the default values will be ignored.
The benefit of using default variables is that it allows you to provide alternate values for variables without overwriting defined variables. This is particularly useful for creating themes or sharing variables across multiple style files.
Note: Local variables override global variables
When you redeclare a variable in a local scope with the same name as a global variable, the local variable overrides the value of the global variable. This allows defining different variable values for specific selectors or mixins without affecting the global scope.
Use the !global keyword to make a local variable a global variable.
SCSS provides the !global keyword, which allows you to explicitly declare a local variable as a global variable. This causes the value of the local variable to be promoted to the global scope where it is declared, overwriting any existing global variable with the same name.
Example:
- // 全局变量
- $primary-color: #3498db;
-
- .button {
- // 局部变量,覆盖全局变量
- $primary-color: #cc582e;
- background-color: $primary-color; // 使用局部变量值
- }
-
- // 使用 !global 将局部变量变为全局变量
- $primary-color: #cddb34;
-
- .button {
- // 使用 !global 将局部变量变为全局变量
- $primary-color: #2ecc71 !global;
- }
-
- body {
- background-color: $primary-color; // 这里使用的是已变为全局的 $primary-color
- }
In the first example, the local variable $primary-color inside the .button selector overwrites the value of the global variable. In the second example, by using the !global keyword, the local variable inside the .button selector is turned into a global variable, thus affecting the variable value in the global scope.
Selector nesting allows you to nest style rules for child selectors inside parent selectors, for example:
- // SCSS代码
- .navbar {
- background-color: #333;
- padding: 10px;
-
- ul {
- list-style: none;
- margin: 0;
- padding: 0;
-
- li {
- display: inline-block;
- margin-right: 10px;
-
- a {
- text-decoration: none;
- color: #fff;
-
- &:hover {
- text-decoration: underline;
- }
- }
- }
- }
- }
In the above code, the .navbar selector contains a nested ul, li, and a child selector. This nested structure makes the style rules clearer and easier to manage.
In SCSS, the & symbol is used to reference the parent selector, which is especially useful in the case of pseudo-classes or pseudo-elements. For example, use &:hover to reference the parent selector of the current selector and add the :hover state style.
- .button {
- background-color: #3498db;
- color: #fff;
- padding: 8px 16px;
- border: none;
- text-align: center;
- text-decoration: none;
- display: inline-block;
-
- &:hover {
- background-color: #2980b9;
- }
- }
SCSS allows multiple levels of selector nesting, for example:
- .container {
- .row {
- .col {
- width: 100%;
- }
- }
- }
In SCSS, in addition to selector nesting, there is also the feature of attribute nesting, which is another feature that makes style sheets neater and easier to manage. Attribute nesting allows related properties to be organized together, similar to the form of an object.
Property nesting can be used to put related properties in a code block, for example:
- .navbar {
- font: {
- family: Arial, sans-serif;
- size: 16px;
- weight: bold;
- }
- margin: {
- top: 10px;
- bottom: 15px;
- }
- padding: {
- left: 20px;
- right: 20px;
- }
- }
In the above example, font, margin, and padding blocks contain related properties. This organization makes the properties in each block clearer and easier to modify and maintain.
In SCSS, inheritance is a very useful feature that allows one selector to inherit the style rules of another selector. This feature can reduce repeated CSS code and make the style sheet more modular and easier to maintain.
Use the @extend keyword to implement selector inheritance. For example:
- %message-shared {
- border: 1px solid #ccc;
- padding: 10px;
- color: #333;
- }
-
- .success-message {
- @extend %message-shared;
- background-color: lightgreen;
- }
-
- .error-message {
- @extend %message-shared;
- background-color: lightcoral;
- }
In the example above, %message-shared is a placeholder selector that defines a set of common styles. .success-message and .error-message inherit the styles of %message-shared and add their own background colors.
Inheritance is particularly suitable for selectors with common characteristics, such as button components, message prompt boxes, etc. Through inheritance, the same style rules can be reused in different scenarios while keeping the code clean and maintainable.
In summary, inheritance in SCSS is a powerful tool that can help you avoid style duplication and keep your code modular and clear, but you need to pay attention to the order and position of selectors when using it, and use placeholder selectors reasonably to maximize its effect.
The placeholder % is a special selector in SCSS, which is usually used to define style rules that can be inherited but will not generate actual CSS output. Specifically:
- %placeholder-selector {
- // 样式规则
- }
In the above example, %placeholder-selector is a placeholder selector that starts with %. It defines a set of style rules, but the corresponding selector name does not appear in the compiled CSS.
- .some-class {
- @extend %placeholder-selector;
- // 可选的额外样式
- }
Using the @extend keyword allows .some-class to inherit the styles of %placeholder-selector. This means that .some-class will apply all the style rules defined in %placeholder-selector and generate the corresponding CSS output.
In summary, the placeholder selector % is a powerful tool in SCSS that can help developers improve the reusability and maintainability of style sheets while reducing unnecessary CSS redundancy.
In SCSS, mixins are another very powerful feature that allows a set of style rules to be encapsulated in a reusable code block and then referenced where needed. Unlike placeholder selectors, mixins can directly generate CSS output, so it is suitable for situations where the same style needs to be used in multiple places.
- @mixin mixin-name($parameter1, $parameter2, ...) {
- // 样式规则使用参数
- }
In the example above, the @mixin keyword defines a mixin called mixin-name, which can accept multiple arguments (if required) and defines a set of style rules within it.
- .some-class {
- @include mixin-name(value1, value2, ...);
- // 可选的额外样式
- }
Using the @include keyword, you can call a mixin in a selector and pass it arguments. This way, .some-class will apply the style rules defined in the mixin and apply the passed argument values to the corresponding argument variables.
- @mixin button-style($background-color, $text-color) {
- display: inline-block;
- padding: 10px 20px;
- border: none;
- border-radius: 4px;
- background-color: $background-color;
- color: $text-color;
- text-align: center;
- text-decoration: none;
- font-size: 16px;
- cursor: pointer;
- transition: background-color 0.3s ease;
-
- &:hover {
- background-color: darken($background-color, 10%);
- }
- }
- .button-primary {
- @include button-style(#3498db, #fff);
- }
-
- .button-secondary {
- @include button-style(#2ecc71, #fff);
- }
In summary, @mixin is a powerful tool for encapsulating and reusing style rules in SCSS. It can significantly improve the maintainability and flexibility of CSS and is suitable for various complex and repetitive style requirements.
In SCSS, conditional statements allow CSS styles to be generated dynamically based on certain conditions. SCSS conditional statements are similar to conditional statements in other programming languages, including @if, @else if, and @else.
The @if statement allows you to generate styles based on a condition. The syntax is as follows:
- $use-rounded-corners: true;
-
- .button {
- @if $use-rounded-corners {
- border-radius: 4px;
- }
- }
In the above example, if the value of the $use-rounded-corners variable is true, the style of the .button class is generated, including border-radius: 4px;. If the condition is false, this part of the style is not generated.
In addition to @if, you can also use @else if and @else to add more conditional branches.
- $button-size: medium;
-
- .button {
- @if $button-size == small {
- padding: 5px 10px;
- } @else if $button-size == medium {
- padding: 10px 25px;
- } @else if $button-size == large {
- padding: 15px 30px;
- } @else {
- padding: 10px 20px; // 默认值
- }
- }
In this example, depending on the value of the $button-size variable, different padding values are selected and applied to the .button class. If no condition matches, the code block in @else is executed.
Conditional statements can also be nested to handle more complex logic.
- $button-style: flat;
- $button-size: medium;
-
- .button {
- @if $button-style == flat {
- background-color: transparent;
- color: #333;
- border: 1px solid #333;
-
- @if $button-size == small {
- padding: 5px 10px;
- } @else if $button-size == medium {
- padding: 10px 25px;
- } @else if $button-size == large {
- padding: 15px 30px;
- } @else {
- padding: 10px 20px; // 默认值
- }
- } @else if $button-style == raised {
- background-color: #3498db;
- color: #fff;
- padding: 10px 20px;
- border-radius: 4px;
- } @else {
- // 默认样式
- background-color: #db6334;
- color: #fff;
- padding: 10px 20px;
- }
- }
In this example, different styles are applied depending on the values of $button-style and $button-size. This nested approach allows complex style rules to be generated based on multiple conditions.
By using conditional statements, more flexible and dynamic style definitions can be implemented in SCSS, and different CSS rules can be generated according to different conditions, thereby improving the maintainability and extensibility of the style sheet.
In SCSS, there are three main loop structures that can be used to generate repeated CSS rules: @for, @each, and @while.
@for loop is used to repeatedly generate patterns according to certain steps and conditions.
Basic syntax:
- @for $i from <start> through <end> {
- // 循环体
- }
Example:
- @for $i from 1 through 3 {
- .item-#{$i} {
- width: 100px * $i;
- }
- }
In the above example, three classes .item-1, .item-2, and .item-3 are generated, setting the width to 100px, 200px, and 300px respectively.
The @each loop is used to traverse list or map type data and generate styles for each element.
Basic syntax:
- @each $var in <list or map> {
- // 循环体
- }
Example:
- $colors: (red, green, blue);
-
- @each $color in $colors {
- .text-#{$color} {
- color: $color;
- }
- }
In this example, three classes .text-red, .text-green, and .text-blue are generated, and their text colors are set to the corresponding color values.
The @while loop repeatedly generates styles based on a condition until the condition is no longer met.
Basic syntax:
- $i: 1;
- @while $i < 4 {
- // 循环体
- $i: $i + 1; // 更新条件
- }
Example:
- $i: 1;
- @while $i < 4 {
- .item-#{$i} {
- width: 100px * $i;
- }
- $i: $i + 1;
- }
This code generates three classes .item-1, .item-2, and .item-3, setting their widths to 100px, 200px, and 300px respectively.
SCSS's three loop structures, @for, @each, and @while, are used to loop by index, traverse lists or map-type data, and generate styles based on conditional loops. These loop structures make SCSS more powerful and flexible, and can generate complex CSS rules as needed.
In SCSS, you can enhance the functionality of your stylesheets using custom functions that accept parameters and return processed values.
In SCSS, use the @function keyword to define a function, which can have parameters and return values. For example, we define a function to calculate the total width of an element's box model:
- @function total-width($padding, $border, $margin, $content-width) {
- @return $padding + $border + $margin + $content-width;
- }
In the example above:
Once a function is defined, it can be used in styles to calculate and generate values as needed. For example:
- .element {
- width: total-width(10px, 1px, 5px, 100px);
- }
In this example, the total-width function will be called with the arguments 10px, 1px, 5px, and 100px. The result returned by the function (116px) will be applied to the width property of .element.
Use SCSS to switch between black and white themes on the page
html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="main.css">
- <title>黑白色主题切换</title>
- </head>
- <body>
- <div class="container">
- <button id="theme-toggle">切换主题</button>
- <div class="box">
- <div class="content">
- <p>这是一些文本内容。</p>
- <p>这是一些文本内容。</p>
- <p>这是一些文本内容。</p>
- <p>这是一些文本内容。</p>
- <p>这是一些文本内容。</p>
- <p>这是一些文本内容。</p>
- <p>这是一些文本内容。</p>
- </div>
- </div>
- </div>
-
- <script src="main.js"></script>
- </body>
- </html>
scss
- // 定义轻主题的样式变量
- $light-theme: (
- background-color: white,
- text-color: black,
- highlight-color: #f0f0f0
- );
-
- // 定义暗主题的样式变量
- $dark-theme: (
- background-color: black,
- text-color: white,
- highlight-color: #333333
- );
-
- // 定义一个混合(mixin)来应用主题样式
- // 参数 $theme: 要应用的主题,是一个包含背景色、文本颜色和高亮颜色的映射(map)
- @mixin theme($theme) {
- background-color: map-get($theme, background-color);
- color: map-get($theme, text-color);
-
- // 为 .box 类应用主题的高亮颜色
- .box {
- background-color: map-get($theme, highlight-color);
- }
- }
-
- // 应用轻主题样式到 body 元素,并添加过渡效果
- body {
- @include theme($light-theme);
- transition: all 0.3s ease;
- }
-
- // 为 body 的 dark 类应用暗主题样式
- body.dark {
- @include theme($dark-theme);
- }
-
- // 设置容器的文本居中和顶部间距
- .container {
- text-align: center;
- margin-top: 20px;
- }
-
- // 配置主题切换按钮的样式
- #theme-toggle {
- padding: 10px 20px;
- cursor: pointer;
- border: none;
- outline: none;
- background-color: #007bff;
- color: white;
- font-size: 16px;
- border-radius: 5px;
- }
-
- // 鼠标悬停在主题切换按钮上时改变背景色
- #theme-toggle:hover {
- background-color: #0056b3;
- }
-
- // 定义 .box 类的基本样式和过渡效果
- .box {
- margin: 20px auto;
- padding: 20px;
- width: 50%;
- border: 1px solid #ccc;
- transition: all 0.3s ease;
-
- // 内容区域的样式配置
- .content {
- p {
- margin: 10px 0;
- }
- }
- }
js
- /**
- * 为主题切换按钮添加点击事件监听器
- * 当按钮被点击时,切换文档主体的黑暗主题样式
- *
- * 该函数通过toggle方法动态切换body元素的'dark'类,从而实现主题的切换。
- * 如果body已经应用了'dark'类,那么点击按钮将移除这个类,反之亦然。
- * 这种方式允许用户在黑暗主题和默认主题之间自由切换。
- */
- document.getElementById('theme-toggle').addEventListener('click', () => {
- document.body.classList.toggle('dark');
- });