I. Define variables

1. Variable declaration and use of CSS

Define three variables :root makes them accessible to all

:root{
  --base: yellow;
  --spacing: 10px;
  --blur: 10px;
}
Copy the code


img{
  filter: blur(var(--blur));
  padding: var(--spacing);
  background: var(--base);
}
Copy the code


You can also change the value of a variable via JS, thereby changing the property

 document.documentElement.style.setProperty(`--The ${this.name}`.this.value + suffix)
 ${this.name} = ${this.name}
Copy the code

2. Variable declaration and use of Less

@charset "utf-8"; // Define variables@test-width:200px;
 @test-height:300px; // Define the style.testDiv{
    width:@test-width;
    height:@test-height;
    background-color: aquamarine;
}
Copy the code

3. Variable declaration and use of Sass

The Sass variable must be$The value of the variable is followed by the name of the variable, and a colon (:Separate (as inCSSProperty setting same) if the value is followed by! defaultIs the default value.

(1) Ordinary variables: they can be used globally after being defined.

Sass syntax:

$fontSize: 12px;
body{
  font-size:$fontSize;
}
Copy the code

CSS output:

body{
    font-size:12px;
}
Copy the code

(2) Default variables: Sass default variables only need to be added after the value! The default.

Sass syntax

$baseLineHeight: 2;
$baseLineHeight: 1.5! default;body{
	line-height: $baseLineHeight;
}
Copy the code


CSS output:

body{
 line-height:2;
}
Copy the code

You can see that the compiled line-height is now 2 instead of our default of 1.5. The value of default variables can be very useful for componentized development.

(3) Special variables: Generally, variables defined by us are attribute values, which can be used directly. However, if variables are attributes or in some special cases, they must be used in the form of #{$variables}

Sass syntax

$borderDirection: top ! default; $baseFontSize:12px! default; $baseLineHeight:1.5! default; // Applies to classes and attributes.border-#{$borderDirection}{
  border-#{$borderDirection}:1px solid #ccc; } // Apply to complex attribute valuesbody{
    font:#{$baseFontSize}/#{$baseLineHeight};
}
Copy the code


CSS output:

.border-top{
  border-top:1px solid #ccc;
}
body {
  font: 12px/1.5;
}
Copy the code

(4) Multi-valued variable: Multi-valued variable is divided into list type and Map type. Simply speaking, list type is a bit like array in JS, while map type is a bit like object in JS.

list
  • List data can be separated by Spaces, commas, or parentheses. The value can be NTH (var,var,index).
  • The list data operation has many other functions such as:length($list).join(list1,list1,list2,[$separator]).append(list,list,value,[$separator]), please refer to moreSass Functions

Sass syntax

$linkColor:#08c # 333! default; // The first value is the default value, and the second mouse-over valuea{
  color:nth($linkColor,1);
  &:hover{
    color:nth($linkColor,2); }}Copy the code

CSS output

a {
  color: #08c;
}
a:hover {
  color: # 333;
}
Copy the code


map
  • Map data is paired with keys and values, which can be lists
  • Format for:$map: (key1: value1, key2: value2, key3: value3)
  • throughmap-get(map,map,map)Etc.
  • See Sass Functions for more information

Definition:

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

Sass compilation

$key-green: green;
$val-green: #fff;
$key-red: red;
$val-red: #ff0000;
$key-info: info;
$val-info: #ff00ff;
$key-success: success;
$val-success: #f66;

//$text: (green: #fff, red: #ff0, info: #f0f);
$text: (
    $key-green: $val-green,
    $key-red: $val-red,
    $key-info: $val-info,
    $key-success:$val-success
);

@each $i, $size in $text {
    .text-# {$i} {
        color: $size; }}Copy the code

CSS output

.text-green {
  color: #fff;
}

.text-red {
  color: #ff0000;
}

.text-info {
  color: #ff00ff;
}

.text-success {
  color: #f66;
}
Copy the code

(5) Global variable: add the value after the variable! globalIs a global variable.

Sass compilation

$fontSize: 12px;
$color: # 333! global;body{
    $fontSize: 14px;
    font-size: $fontSize;
}
p{
    font-size: $fontSize;
    color: $color;
}
Copy the code


CSS output

body {
  font-size: 14px;
}
p {
  font-size: 12px;
  color: # 333;
}
Copy the code

Here we set two variables, then reset them inside the body. The difference is that for the $color variable, we set it! Global. After compiling the CSS, you can see that the value of font-size is different, but the value of color is the same. By default, variables in the selector are local variables, and only Settings are available! Global becomes a global variable after global.

2. The commonness of Less and Sass

Mixins: the class of classes

Mixins are rulesets of one set of properties mixed into another set of rules to define reusable styles, such as Flex layouts, and are used frequently in daily development.

Mixed use of Less

.flex() {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.cell-line {
   .flex(a);font-size: 16px;
}
Copy the code

Mixed use in Sass

// Define mixed instructions, syntax:@mixinAdd the name and style @mixin flex() {display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center; } // Reference mixed instructions, syntax:@includeThen add the name and parameters (optional). Cell-line {@include flex;
   font-size: 16px;
}
Copy the code

2. Parametric: A class that passes parameters like a function

Parametric: Parameter is passed to the class like a function, and the default value can be set when it is defined, otherwise the default value is used.

Parameters in Less are used together

.flex(@direction: row, @items: initial, @content: initial) {
    display: flex;
    flex-direction: @direction;
    align-items: @items;
    justify-content: @content;
}
.cell-line {
  .flex(row, center);
  font-size: 16px;
}
Copy the code

Parameters in Sass are mixed

@mixin flex($direction: row, $items: initial, $content: initial) {
    display: flex;
    flex-direction: $direction;
    align-items: $items;
    justify-content: $content;
}
.cell-line {
  @include flex(row, center);
  font-size: 16px;
}
Copy the code

Nested Rules: classes are Nested within classes to reduce duplicate code

Nested means to nest its sub-selectors in a selector to make its structure clear and increase the readability of code.

Nesting rules for Less

.list {
  background: #fff;
  .item {
     color: #de432a}}Copy the code

(1) In nesting, & represents the parent selector, not the child selector, and the same is true in Sass.

Less grammar

a {
  color: blue;
  &:hover {
    color: green; }}Copy the code


a {
  color: blue;
}
a:hover {
  color: green;
}
Copy the code

(2) @ rules (such as @media or @supports) can be nested in the same way as selectors. The @ rule is placed first, and the relative order of other elements in the same rule set remains the same. Bubbling, “bubbling.

Less grammar

.component {
  width: 300px;
  @media (min-width: 768px) {
    width: 600px;
    @media  (min-resolution: 192dpi) {
      background-image: url(/img/retina2x.png); }}@media (min-width: 1280px) {
    width: 800px; }}Copy the code


.component {
  width: 300px;
}
@media (min-width: 768px) {
  .component {
    width: 600px; }}@media (min-width: 768px) and (min-resolution: 192dpi) {
  .component {
    background-image: url(/img/retina2x.png); }}@media (min-width: 1280px) {
  .component {
    width: 800px; }}Copy the code

Note: This example was introduced from the official website.Nested rules

Attributes of Sass are nested

Font-size, font-family, font-weight, and so on all use the font as the namespace of the attribute. In Sass, nested attributes are allowed in the namespace.

Sass syntax

.list {
  font {
    size: 12px;
    weight: bold;
    family: Arial, Tahoma, 'Microsoft Yahei'.'\5b8b\4f53', sans-serif; }}Copy the code

The CSS to compile

.list {
  font-size: 12px;
  font-weight: bold;
  font-family: Arial, Tahoma, 'Microsoft Yahei'.'\5b8b\4f53', sans-serif;
}
Copy the code

4. Operations: Mathematical calculations in the CSS

The arithmetic operators +, -, *, and/can operate on any number, color, or variable. In +, – operations, if the unit is different, the unit conversion is carried out according to the unit type of the operand on the left.

Less operation using

  @bgColor: #112233 + #134; / / for the results# 225577
Copy the code

Calc special case

To be compatible with CSS, calc() in Less does not evaluate mathematical expressions, but evaluates variables and mathematical formulas in nested functions

@topHeight: 46px;
.list {
  height: calc(100vh - @topHeight);
}
Copy the code

Sass operation is used

p {
  color: # 010203 * 2; / / for the resultscolor: # 020406; } // Note: The calculation must be the same alpha value, i.e. both RGBA and HSLA.Copy the code

From the perspective of CSS optimization, avoid using CSS expressions. A CSS expression is executed repeatedly, and should be used only if the CSS properties are evaluated hundreds or thousands of times.

5. Color Function: You can edit your colors

Color function operations, the colors are first converted to HSL color space and then manipulated at the channel level.

Less

p {
  color: hsl(90.100%.50%} // See Less for more information[Color function](https://Less.bootcss.com/functions/#color-definition-functions)
Copy the code

Sass

p {
  color: hsl(0.100%.50%); } // CSS compiles to:p {
  color: #ff0000;
}
Copy the code

6. Namespaces: Grouping styles so they can be easily invoked

Packaging variables or mixed modules can help prevent repeated use of CSS and property sets.

@colorBg: #f51861;
#bundle {
  .button{
    color: #fff;
    background: @colorBg;
    &:hover {
      background: green; }}.tab{... }.cell-line{... }} // usep {
  padding: 10px;
  #bundle .button(a); } // Note: Sass is the same with a slightly different syntax.Copy the code

7. Scope: Modify the style locally

The scope of Less is similar to that of the CSS. Variables and attributes are searched locally. If none is found, variables and attributes are inherited from the parent scope.

@color: # 333;.list {
  @color: #f51861;
  .item {
    color:@color; // #f51861}}Copy the code


Sass supports two types of variables: local variables and global variables. In general, global variables are outside the selector and local variables are inside the selector.

@mixin button-style {
  $btn-bg-color: lightblue;
  color: $btn-bg-color;
}
.button {
  @includeButton-style} // CSS compile.button {color: lightblue;
}
Copy the code

What happens if you use this variable in a selector?

.btn {
  background: $btn-bg-color; // Undefined constant '$btn-bg-color', because the variable does not exist globally. }Copy the code

8.JavaScript Evaluation: Assign values using JavaScript expressions in CSS styles

Less

@some: foo;
div {
  margin: if((2 > 1), 0.3px);
  color:  if((iscolor(@some)), @some, black); } / / CSS compilationdiv {
  margin: 0;
  color:  black;
}
Copy the code

Sass

p {
  @if 1 + 1= =2 { border: 1px solid; }
  @if 5 < 3 { border: 2px dotted; }
  @if null  { border: 3pxdouble; }} // CSS compilesp {
  border: 1px solid;
}
Copy the code

3. Relevant interview questions

1. What is a CSS preprocessor?

CSS preprocessors style Web pages in a specialized programming language and then compile them into normal CSS files for use by projects. The CSS preprocessor adds programming features to the CSS, regardless of browser compatibility. The main CSS preprocessor languages include Sass, Less, and Stylus.

Implementation principle:

  • Retrieves the analysis tree of the DSL source code
  • Transform an analysis tree with dynamically generated related nodes into a static analysis tree
  • Convert the static analysis tree to the static analysis tree of CSS
  • Convert the static analysis tree of CSS to CSS code

2. What is a CSS post-processor?

The CSS is processed and the CSS preprocessor is generated. It belongs to the CSS preprocessor in the broad sense and can automatically handle compatibility problems of the CSS. Take Autoprefixer as an example:

.container {
  display: flex;
}
.item {
  flex: 1;
}
Copy the code

Compile the above standard CSS into a production environment CSS that handles compatibility:

.container {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}
.item {
  -webkit-box-flex: 1;
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
}
Copy the code

As you can see, the pre – and post-compile code is CSS

Realize the principle of

  • The source code is parsed as CSS to obtain the analysis tree
  • Post-processing the analysis tree of the CSS
  • Convert the analysis tree of CSS to CSS code

3. The difference between Less and Sass

  1. Implementation: Less is based on JavaScript, so Less is handled on the client side; Sass is Ruby based and is handled on the server side.
  2. Variables: Less uses @, Sass uses $, Sass uses @mixin and @include, respectively.
  3. File extensions: Less suffix “.less “, Sass3.0 before the suffix “.sass “, Sass3.0 after the suffix “SCSS”
  4. Grammatical differences, listed above, will not be repeated.

4. How many ways can YOU use Sass?

  • As a command line tool.
  • As a standalone Ruby module.
  • As a plug-in for any framework with Rack enabled.

5. How many ways are there to use Less?

  • Through the command line.
  • Use third-party tools.
  • You can download Less as a script file for your browser.

6. How to use Less/Sass in Vue project?

  • NPM/yarn installation package
  • Configure in webpack.config.js
{
    test: /\.less/,
    include: /node_modules/,
    loaders: ['style-loader'.'css-loader'.'less-loader'],},Copy the code
  • In the vue file, define the lang as less, or define the file with the suffix less.
<style scoped lang="less"></style>
Copy the code

7. What does extend do in Less/Sass?

Extend in Less is its pseudo-class for selecting another selector style in one selector. In Sass, @extend does the same.

//less
h2 {
   &:extend(.style);
   font-style: italic;
}
.style {
   background: green; } / / CSS compilationh2 {
  background: green;
  font-style: italic;
}
//Sass
.message  {
  border: 1px solid #ccc
  padding: 10px
  color: # 333
}
.success  {
  @extend .message
  border-color: green
}
Copy the code

8. What are the advantages of Less/Sass? (Which one would you choose?)

Advantages of Less:

  • Less is a CSS preprocessor. When compiled, it generates simple CSS for use in browsers.
  • Less supports cross-browser compatibility.
  • Because Less uses nesting, code is shorter, cleaner, and organized in a specific way
  • Because Less uses variables, maintenance is faster.
  • Less provides a series of operators that make coding faster and Less time-consuming.
  • Less provides the @mport rule so that we can easily work with external files. Note: Imports are required because many people split stylesheets into multiple files rather than putting them into a single file.
  • Less provides merge attributes. The most exciting feature of Less is that it accepts multiple values, such as transform, transition, and box-shadow.
  • Less is written in JavaScript and can compile faster than other preprocessors of CSS.

Advantages of Sass:

  • Sass makes it easy to use logical statements such as loops and conditions, and to write reusable methods.
  • Sass users can use some great features such as cross-browser support, older browser hacking and dynamic Sprite Map generation.
  • Compass also provides the ability to add external frameworks such as Bootstrap, Blueprint.
  • Sass provides you with convenient feature writing tools.

9. What are the ways to optimize and improve performance of the CSS?

(1) Loading performance:

(1) CSS compression: the written CSS is packaged and compressed, which can reduce a lot of volume. (2) CSS single style: When the bottom margin and left margin are needed, most of the time choose :margin:top0bottom0; But the margin – bottom: bottom; margin-left:left; Execution is more efficient. (3) Reduce the use of @import and recommend the use of link, because the latter is loaded together when the page is loaded, while the former is loaded after the page is loaded.

(2) Selector performance:

(1) keyselector. The last part of the selector is the key selector (that is, the part used to match the target element). CSS selectors are matched from right to left. When using descendant selectors, the browser iterates over all child elements to determine if they are specified, and so on; (2) Do not add labels to rules if they have ID selectors as their key selectors. Filter out extraneous rules (so the style system doesn’t waste time matching them). (3) Avoid the use of wildcard rules, such as *{} calculation times surprising! Select only the elements you need. (4) Select as few tags as possible and use class instead. (5) Use descendant selectors as little as possible to reduce the weight value of selectors. Descendant selectors have the highest overhead. Try to keep the depth of the selectors to a minimum of three layers, and use more classes to associate each tag element. (6) Know which attributes can be inherited, and then avoid respecifying rules for those attributes.

(3) Rendering performance:

(1) Carefully use high-performance attributes, such as floating and positioning. (2) minimize page rearrangement and redrawing. (3) Empty rule removal: {}. The reason for empty rules is generally to reserve style. Removing these empty rules will definitely reduce CSS document size. (4) When the attribute value is 0, no unit is added. (5) Attribute value is floating decimal 0.**, can omit the 0 before the decimal point. (6) Standardize various browser prefixes: those with browser prefixes come first. Standard attributes come later. (7) Do not use the @import prefix, which will affect the loading speed of CSS. (8) Optimize nesting of selectors and try to avoid too deep hierarchy.

Recommended reading:

  1. Sass official documentation: www.sass.hk/docs/

  2. Less Official document: less.bootcss.com/#%E6%A6%82%…

  3. 104 CSS interview questions to help you fill in the gaps


A tool for editing Sass online: Sassmeister is introduced