Sass Advanced Guide--Write a more elegant style sheet

I thought I already knew it. I basically used the sasswriting style when writing projects in the company before, which was very smooth. Until a while, I was going Element Plusto design the engineering structure of my own component library with reference. When I saw Element Plusthose elegant sassusages, I began to feel ashamed of my shallowness and ignorance. This started to study systematically sass. During this period, I wanted to write some learning and sharing many times, but all of them ended up without a problem due to various things. Today, I finally sneaked a little time out of my busy schedule, just in time to share my encouragement with you.

1. Introduction

As an extremely mature csspreprocessor, it sasshas many special functions, which help us write more elegant and concise style code. It cssintroduced style variables before, and also supports functions such as nesting, functions, mixing, and command control, which greatly expands the style gameplay.

sassThere are two syntax forms: SCSSand Sass.

Among them SCSS, it is a format that is widely used at present. It only expands on the grammar basis CSS3of .SassCSS hacksvendor-specific syntax.scss

It isSass the earliest grammatical format, using indentation instead of curly braces, and newlines instead of semicolons. The format is particularly concise and writing is more convenient. This format also supports all the functions, but it uses a different expression Sassin some places , and its file extension is named .SCSS.sass

Either format can be imported (@import) into a file of another format for use, and can also be sass-convertconverted to another format through a command-line tool.

# Sass转为SCSS
sass-convert style.sass style.scss
# SCSS转为Sass
sass-convert style.scss style.sass 

I won’t introduce the Sassinstallation and use of it here. After all, most projects are now webpackpackaged and built through other construction tools, supplemented by corresponding and loaderother tools to assist in compilation. There should be very few projects that need to use sasscommands on the command line to compile style files.

However, the encoding format is worth mentioning. As with CSS, you can use @hcarsetto declare a specific encoding format: insert it at the beginning of the style file (at the first character) @charset "encoding-name", and Sassthe file will be compiled according to the given encoding format. Of course, the encoding format used must be convertible into a Unicodecharacter set. SassOutput the file in UTF-8encoding , and add a declaration to the output file CSSif non-characters appear in the compiled file .ASCII@charset

2. Basic function expansion

1. Nested rulesNested Rules

SassIt supports CSSembedding one set of styles into another set of CSSstyles, and the inner style will use the outer selector as the parent selector.

#main p {
  color: #00ff00;
  width: 97%;
  .redbox {
    background-color: #ff0000;
    color: #000000;}
} 

This would be Sasscompiled as follows CSS:

#main p {
  color: #00ff00;
  width: 97%; 
}
#main p .redbox {
  background-color: #ff0000;
  color: #000000; 
} 

The nesting function greatly reduces the amount of code, we no longer have to repeatedly write cumbersome parent selectors, and it is easy to manage.

2. Parent selector &( Referencing Parent Selectors: &)

In nesting, if you need to refer to the parent selector, such as when setting a :hoverstyle for an element, or when bodyan element has a certain value classname, it can be &used to refer to the parent selector, that is, its outer selector.

a {
  font-weight: bold;
  text-decoration: none;
  // & 引用父元素&:hover { text-decoration: underline; }
  // body.firefox 可以直接引用
  body.firefox & { font-weight: normal; }
} 

will be Sasscompiled as follows CSS:

a {
  font-weight: bold;
  text-decoration: none; 
}
a:hover {
  text-decoration: underline; 
}
body.firefox a {
    font-weight: normal; 
} 

&Must be the first character of a selector, but it can be followed by suffixes to generate compound selectors :

#main {
  color: black;
  // #main-sidebar 字符串拼接,这就有点好玩了&-sidebar { border: 1px solid; }
} 

This would be compiled to:

#main {
  color: black; 
}
#main-sidebar {
  border: 1px solid; 
} 

3. Attribute nestingNested Properties

Some CSSfollow the same namespace ( namespace), such as font-family, font-size, font-weightboth have fontnamespaces as attributes. At this time, for simplicity of writing and convenient management, Sassattributes are allowed to be nested in namespaces:

.funky {
  // 注意命名空间这里要加冒号
  font: {
    family: fantasy;
    size: 30em;
    weight: bold;}
} 

compiles as follows CSS:

.funky {
  font-family: fantasy;
  font-size: 30em;
  font-weight: bold; 
} 

Among them, the namespace can also contain its own attribute values:

.funky {
  // font-size/line-height
  font: 20px/24px {
    family: fantasy;
    weight: bold;}
} 

compiles to:

.funky {
  /* font-size/line-height */
  font: 20px/24px;
  font-family: fantasy;
  font-weight: bold; 
} 

4. Placeholder selector %foo( Placeholder Selectors: %foo)

Placeholder selectors are similar idto selectors and classselectors, except that the symbol is %, and must be @extendcalled through instructions, otherwise they will not participate in Sassthe compilation.

5. NotesComments

SassBoth single-line comments //and multi-line comments are supported /* */. Multi-line comments are fully output to the compiled CSSfile . Will !be the first character of a multi-line comment means to keep this comment in the compressed output mode and output it to the file, which is usually used to add copyright information. Interpolation statements ( ) can output variable values ​​in multi-line comments. (Use for interpolation.)CSSinterpolation#{$val}

// Sass
$version: "1.2.3";
/* This CSS is generated by My Snazzy Framework version #{$version}. */
// 编译为CSS:
/* This CSS is generated by My Snazzy Framework version 1.2.3. */ 

3. Advanced function expansion

1.SassScript

SassProvides a SassScriptpowerful function named , which can be applied to any attribute, allowing attributes to use additional functions such as variables and arithmetic operations.

1.1Interactive Shell

Interactive ShellFeatures that can be tested at the command line SassScript. Enter on the command line sass -i, and then enter what you want to test to SassScriptsee the output.

sass -i
>> "Hello, Sassy World!"
"Hello, Sassy World!"
>> 1px + 1px + 1px
3px
>> #777 + #777
#eeeeee
>> #777 + #888
white 

1.2 Variables$ Variables: $

Using variables is very simple:

// 声明变量
$width: 5em;
#main {// 使用变量
  width: $width;
} 

Variables have block-level scope , and variables within nested rules are local variables that can only be used within nested rules. Global variables can be used anywhere. Adding !globala declaration turns a local variable into a global variable .

// Sass
#main {// !global声明,转换为全局变量
  $width: 5em !global;
  width: $width;
}
#sidebar {
  // 使用全局变量
  width: $width;
}
// 编译为CSS:
#main {
  width: 5em;
}
#sidebar {
  width: 5em;
} 

1.3 Data TypesData Types

SassScript7The main data types are supported :

  • Numbers, with units, 1, 2, 3, 6, 10pxetc.;
  • string (both quoted and unquoted are supported), "foo", "bar", baz;
  • color, blue, #04a3f9, rgba(255,0,0,0.5)etc;
  • boolean, true, false;
  • NULL, null;
  • Array ( list), with spaces or commas as delimiters, 1.5em 1em 0 2em, Helvetica, Arial, sans-serif;
  • maps, which is equivalent to JSwhere Object, (key1: value1, key2: value2).

In addition, other attribute values SassScript​​are also supported , such as character sets, or declarations, but these are not treated specially, but are treated as unquoted strings.CSSUnicode!important

1.3.1 Strings

SassScriptBoth quoted strings ( ) and unquoted strings ( ) arequoted strings supported . These two strings will not be converted to each other at compile time, except for one case: when using ( ), the quoted string will be compiled into an unquoted string, which is convenient for quoting the selector name in .unquoted strings#{}interpolationmixin

// Sass
@mixin firefox-message($selector) {
  body.firefox #{$selector}:before {
    content: "Hi, Firefox users!";}
}
@include firefox-message(".header");
// 编译为CSS
body.firefox .header:before {
  content: "Hi, Firefox users!"; 
} 
1.3.2 array ( lists)

An array refers to Sasshow to handle a series of values CSS​​in margin: 10px 15px 0 0or font-face: Helvetica, Arial, sans-serifsuch separated by spaces or commas. In fact, individual values ​​are also treated as arrays containing only one value.

The array itself does not have many functions, but Sass list functionsit brings many new functions to the array: nthfunctions can directly access an item in the array; joinfunctions can connect multiple arrays together; appendfunctions can add new values ​​​​to the array; @eachfunctions can traverse each item in the array.

Arrays can contain sub-arrays: For example 1px 2px, 5px 6px, is contains two1px 2px arrays of and . 5px 6pxIf the inner and outer arrays use the same separation method, you need to use parentheses to wrap the inner layer, eg (1px 2px) (5px 6px). Parentheses will not be preserved during compilation, so no matter which way they are written, 1px 2px, 5px 6pxor (1px 2px) (5px 6px)the final compilation result is the same, but they Sasshave different meanings in the file, the former means an array containing four values, and the latter means an array containing two It can be said that the parentheses emphasize the concept of "grouping".

()Used to represent an empty array, and can also represent empty map. Empty arrays will not be compiled directly CSS, and if there are empty arrays or null values ​​in the array, they will be cleared at compile time. Such as 1px 2px () 3pxor 1px 2px null 3px. Comma-separated arrays are allowed to retain the trailing comma, which is meant to emphasize the structural relationship of the array, especially when it is necessary to declare an array containing only a single value. For example (1,)represents 1an array containing only .

1.3.3maps

mapis a collection of key-value pairs, keyand valueboth can be arbitrary SassScriptobjects. It and listboth operate with functions. For example, map-getfunctions can be used to look up key -values, functions can map-mergebe used to add new key-value pairs, and @eachdirectives can be used to add styles to each key-value pair. mapIt can be used anywhere it can be used list, but not vice versa. When mapused listin functions, it is treated as key1 value1, key2 value2an array of the form.

1.3.4 Color

Any CSScolor expression returns a SassScriptcolor value. unquoted stringsThis contains a large number of named colors (often indistinguishable from unquoted strings ).

1.4 OperationOperations

All data types support the equality operation ==OR !=, in addition, each data type also has its own operation mode.

1.4.1 Numerical operationsNumber Operations

SassScriptSupports addition, subtraction, multiplication, and division as well as rounding? operations ( +, -, *, /, %), converting values ​​between units when necessary. The relational operator ( >, <, >=, <=) can also be used for numeric operations.

// Sass
p {
  width: 1in + 8pt;
}
// 编译为:
p {
  width: 1.111in; 
} 
  • division operation/

The division operation deserves a separate mention. Because /symbols CSSusually play the role of separating numbers in . In SassScript, /not only for separating numbers, but also for division operations. In the following three cases, /it is considered a division operation:

  • when the value or part of a value is a variable or the return value of a function;
  • When the value is wrapped in parentheses;
  • When the value is part of an arithmetic expression.
// Sass
p {
  font: 10px/8px;             // 普通的CSS
  $width: 1000px;
  width: $width/2;            // 使用了变量,是除法运算
  width: round(1.5)/2;        // 函数返回值,是除法运算
  height: (500px/2);          // 使用圆括号,是除法运算
  margin-left: 5px + 8px/2px; // 算数运算表达式的一部分,是除法运算
}
// 编译为CSS
p {
  font: 10px/8px;
  width: 500px;
  height: 250px;
  margin-left: 9px; 
} 

If you need to use a variable and don't want it to /be used as a division operator, you can #{}wrap the variable with:

// Sass
p {$font-size: 12px;$line-height: 30px;font: #{$font-size}/#{$line-height};
}

// 编译为CSS
p {font: 12px/30px; 
} 
1.4.2 Color value operationColor Operations

The operation of the color value is calculated in sections, that is, R, G, Bthe values ​​​​are calculated separately.

p {
  color: #010203 + #040506;
} 

Computed in pieces 01 + 04 = 05 02 + 05 = 07 03 + 06 = 09, then compiled as:

p {
  color: #050709; 
} 

can be used color functions, which is a bit more convenient than color calculations.

Color values ​​can also be combined with numerical operations:

p {
  color: #010203 * 2;
}
// 计算 01 * 2 = 02 02 * 2 = 04 03 * 2 = 06,然后编译为:
p {
  color: #020406; 
} 

It should be noted that if the color value contains alpha channel, the color value involved in the calculation must have the same alphavalue to perform the operation, because the arithmetic operation will not act on the alphavalue.

p {
	// 需要保证有相同的alpha值color: rgba(255, 0, 0, 0.75) + rgba(0, 255, 0, 0.75);
} 

The value in the color value alphacan be adjusted through the function opacityor transparentize.

// Sass
$translucent-red: rgba(255, 0, 0, 0.5);
p {
  color: opacify($translucent-red, 0.3);
  background-color: transparentize($translucent-red, 0.25);
}
// 被编译为:
p {
  color: rgba(255, 0, 0, 0.8);
  background-color: rgba(255, 0, 0, 0.25); 
} 
1.4.3 String operationsString Operations

Use a +concatenation string; +the value on the left dominates whether the final compiled result is quoted or unquoted.

When the operation expression is used in conjunction with other values, use spaces as connectors:

p {
  margin: 3px + 4px auto;
}
// 编译为:
p {
  margin: 7px auto; 
} 

You can #{}insert dynamic values ​​using:

$value: null;
p:before {content: "I ate #{$value} pies!";
}

// 编译为CSS:
p:before {content: "I ate pies!"; 
} 
1.4.4 Boolean operationsBoolean Operations

Boolean operations support and, or, not.

1.4.5 Array operations

Arrays do not support direct operations and can only list functionsbe manipulated using.

1.5 Parentheses(Parentheses)

Parentheses are counted first.

1.6 FunctionsFunctions

SassScriptThere are many functions built in, some can even be CSScalled using ordinary statements:

p {
  color: hsl(0, 100%, 50%);
}
// 编译为:
p {
  color: #ff0000; 
} 
  • keyword argumentsKeyword Arguments

SassFunctions allow keyword arguments, the above example can be written as:

p {
  color: hsl($hue: 0, $saturation: 100%, $lightness: 50%);
} 

SassThere are many built-in functions, so I won't expand them here.

1.7 Interpolation StatementsInterpolation #{}

Variables can #{}be used in selectors or property names via:

$name: foo;
$attr: border;
p.#{$name} {#{$attr}-color: blue;
}

// 编译为:
p.foo {border-color: blue; 
} 

SassScriptin 1.8&

&Represents the parent selector. As follows, &the value of ((".foo.bar" ".baz.bang"), ".bip.qux").

.foo.bar .baz.bang, .bip.qux {$selector: &;
} 

If there is no parent selector, &the value is null. This can be applied in mixinto detect if there is a parent selector:

@mixin does-parent-exist {
  @if & {
    // 有父选择器
  &:hover {
      color: red;
  }} @else {
    // 没有父选择器
    a {
      color: red;
  }}
} 

1.9 Variable default value ( Variable Defaults):!default

Adding at the end of a variable !defaultcan be used to assign a value to !defaulta variable that has not been assigned a declaration. nullAssignment will only work if the variable has not been assigned a value or is assigned a null value !default.

$content: "First content";
// 变量已被赋值,无效
$content: "Second content?" !default;
$new_content: "First time reference" !default;
#main {
  content: $content;
  new-content: $new_content;
}
// 编译为:
#main {
  content: "First content";
  new-content: "First time reference"; 
} 

2. @-Ruleswith the command ( Directives)

SassAll CSS3 @-Rules, as well as Sassspecific directives ( directives) are supported.

2.1@import

SassExtended @importfunctionality to make it possible to import .scssand .sassfile. The imported files will be merged and compiled into the same CSSfile. Additionally, variables contained in the imported file may or mixinmay not be available in the imported file.

Generally, the file @importis found Sassand imported, with the following exceptions, which are treated as normal CSSsyntax:

  • The file extension is .css;
  • Filenames http://start with;
  • The filename is url();
  • @importcontains media queries.

It is allowed to import multiple files at a time. When no extension is written, it will try to find .scssor .sassthe file with the same name.

@import "rounded-corners", "text-shadow"; 

Import files can also use interpolation statements #{}, but only for CSSthe url()import method.

$family: unquote("Droid+Sans");
@import url("http://fonts.googleapis.com/css?family=#{$family}");
// 编译为:
@import url("http://fonts.googleapis.com/css?family=Droid+Sans"); 

@importsThere are also two special usages: partials and nesting .

  • Diaphragm ( Partials)

Sometimes you want to import Sassa file, but don't want to compile it as CSS, you can add an underscore before the file name, which will tell Sassyou not to compile it. Note that the underscore is not required in the import statement. For example, if the file is named _colors.scss, the following code imports the _colors.scssfile and it will not be compiled as CSS.

@import "colors"; 

It should be noted that if there are files with the same name that contain leading underscores and files that do not contain leading underscores, the files that add underscores will be ignored.

  • nesting@import

In most scenarios, we use it at the top level of the file @imports. In fact, nesting can also be @importsnested into CSSstyles or @media. The difference from using it in the top layer is that the style imported in this way can only appear in the nested layer, which can be understood as "local scope".

// example.scss
.example {
  color: red;
} 
// main.scss
#main {
  @import "example";
} 

will eventually be compiled to:

#main .example {
  color: red;
} 

However, it should be noted that there should be no top-level instructions such as , etc. @importin the files imported by this nested form .@mixin@charset

2.2@media

Sassis the @mediasame CSSas in , with the addition of new features:

  • It is allowed to be CSSnested within rules. When it @mediais nested into CSSa rule, when it is compiled, it will be compiled to the outermost layer of the file and contains the parent selector when it was nested before, which is very convenient.
// Sass
.sidebar {
  width: 300px;
  @media screen and (orientation: landscape) {
    width: 500px;}
}
// 编译为
.sidebar {
  width: 300px; 
}
@media screen and (orientation: landscape) {
  .sidebar {
    width: 500px; } 
} 
  • @mediaNesting is allowed queries, which is automatically added at compile time and.
@media screen {
  .sidebar {
    @media (orientation: landscape) {
      width: 500px;
  }}
}
// 编译为
@media screen and (orientation: landscape) {
  .sidebar {
    width: 500px; } 
} 
  • You can use SassScript(variable, function, etc.) instead of the name or value of the condition.
$media: screen;
$feature: -webkit-min-device-pixel-ratio;
$value: 1.5;
@media #{$media} and ($feature: $value) {
  .sidebar {
    width: 500px;}
}
// 编译为
@media screen and (-webkit-min-device-pixel-ratio: 1.5) {
  .sidebar {
    width: 500px; } 
} 

2.3@extend

  • @extendA selector can be made to inherit the style of another selector via .
.error {
  border: 1px #f00;
  background-color: #fdd;
}
.error.intrusion {
  background-image: url("/image/hacked.png");
}
.seriousError {
  // 继承,此时所有使用到 .error 的样式都会被继承过来
  @extend .error;
  border-width: 3px;
}
// 编译为
.error, .seriousError {
  border: 1px #f00;
  background-color: #fdd; }
.error.intrusion, .seriousError.intrusion {
  background-image: url("/image/hacked.png"); 
}
.seriousError {
  border-width: 3px; 
} 
  • Placeholder Selectorsplaceholder selector

Sometimes, it is necessary to define a set of styles for inheritance, not for a certain element, and we hope that it will not be Sasscompiled and output separately. This kind of scene occurs more often when making a Sassstyle library. Thus was born the placeholder selector. Its use is almost identical idto selector or classselector, the selector notation is %. When used alone, placeholder selectors are Sassignored and not compiled into the output file.

// 不会被编译到输出文件中
#context a%extreme {
  color: blue;
  font-weight: bold;
  font-size: 2em;
} 

It needs to @extendbe used by:

.notice {
  @extend %extreme;
}
// 被编译为
#context a.notice {
  color: blue;
  font-weight: bold;
  font-size: 2em; 
} 
  • !optionalstatement

Using !optionaldeclarations, it is possible @extendnot to generate new selectors.

// 不可以,因为没有 .notice
a.important {
  @extend .notice
}
// 可以
a.important {
  @extend .notice !optional;
} 
  • used in the command@extend

In order to avoid generating a lot of useless code, extend ( @extend) in the instruction, and limit the extension to selectors in the same instruction level.

@media print {
  .error {
    border: 1px #f00;
    background-color: #fdd;}
  .seriousError {
    // 可以
    // .error 同在一个 @meida层级中
    @extend .error;
    border-width: 3px;}
}
// 以下为反面栗子
.error {
  border: 1px #f00;
  background-color: #fdd;
}
@media print {
  .seriousError {
    // 不可以, .error 不在当前的@meida指令层级中
    @extend .error;
    border-width: 3px;}
} 

2.4@at-root

Use @at-rootdirectives to hoist selected selectors to the outermost level.

.parent {...
  @at-root .child { ... }
}
// 编译为
.parent { ... }
.child { ... } 
  • It can be a block-level structure containing multiple selectors.
.parent {...
  @at-root {
    .child1 { ... }
    .child2 { ... }}
  .step-child { ... }
}
// 编译为
.parent { ... }
.child1 { ... }
.child2 { ... }
.parent .step-child { ... } 
  • Use with:xxx yyy ...or without:xxx yyy ...to ensure that the outer directive is valid for the selector promoted to the outermost layer:
// without:
@media print {
  .page {
    width: 8in;
    // without: media 让选择器不受外层的@media影响
    @at-root (without: media) {
      color: red;
  }}
}
// 编译为
@media print {
  .page {
    width: 8in;}
}
.page {
  color: red;
} 

3. Control commandsControl Derectives

Control directives are used to reference styles under certain conditions.

3.1if()

The built-in iffunction can be used in any SassScriptscripting context.

3.2@if

@ifThe condition is met when the return value of the expression of the instruction is not falseor null. @else ifCan be connected later @else.

$type: monster;
p {
  @if $type == ocean {
    color: blue;} @else if $type == matador {
    color: red;} @else if $type == monster {
    color: green;} @else {
    color: black;}
}
// 编译为
p {
  color: green; 
} 

3.3@for

This directive has two formats: @for $var from <start> through <end>, or @for $var from <start> to <end>. Both contain the starting point <start>, the difference is that toit does not contain <end>, but throughcontains <end>. Also, $varcan be any variable, but <start>and <end>must be integers.

@for $i from 1 to 3 {
  .item-#{$i} { width: 2em * $i; }
}
// 编译为
.item-1 {
  width: 2em; 
}
.item-2 {
  width: 4em; 
} 

3.4@each

@eachCommand format:@each $var in <list>

@each $animal in puma, sea-slug, egret, salamander {.#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');}
}
// 编译为
.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'); } 
  • Multiple variables can be applied at the same time , which is handy when writing styles that have similar forms but different values:
@each $animal, $color, $cursor in (puma, black, default),
                                (sea-slug, blue, pointer),
                                (egret, white, move) {.#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
    border: 2px solid $color;
    cursor: $cursor;}
}
// 编译为
.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; } 
  • Since mapsit will be treated as an array lists, @eachcan alsomap be used :
@each $header, $size in (h1: 2em, h2: 1.5em, h3: 1.2em) {#{$header} {
    font-size: $size;}
}
// 编译为
h1 {
  font-size: 2em; }
h2 {
  font-size: 1.5em; }
h3 {
  font-size: 1.2em; } 

3.5@while

whileCirculation, I understand.

$i: 6;
@while $i > 0 {
  .item-#{$i} { width: 2em * $i; }
  // 更改条件变量
  $i: $i - 2;
}
//编译为
.item-6 {
  width: 12em; }
.item-4 {
  width: 8em; }
.item-2 {
  width: 4em; } 

4. Mixed commands ( Mixin Directives)

mixinUsed to define reusable styles.

4.1 Defining Mixed Instructions @minin( Defining a Mixin: @mixin)

After @mixinadding the name and style, you can define the mixed instruction. Note that you need to include selectors and attributes, and you can also use &to refer to the parent selector.

// 定义名为 clearfix 的混合指令
@mixin clearfix {
  display: inline-block;
  // & 指代父选择器。注意,这个混合指令里虽然它没有父选择器,
  // 但是混合指令使用的地方,可以产生父选择器&:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;}
  // 这里的 & 同理* html & { height: 1px }
} 

4.2 Reference mixed instructions @include( Including a Mixin: @include)

  • Use @include MixinNameto quote a mixin directive:
.page-title {
  // 引用混合指令,将 clearfix 中的规则混入到 .page-title 中
  @include clearfix;
  padding: 4px;
  margin-top: 10px;
} 
  • It can also be directly referenced and mixed in at the outermost level, without defining attributes and having no parent selector to refer to:
@mixin silly-links {
  a {
    color: blue;
    background-color: red;}
}
@include silly-links;
//编译为
a {
  color: blue;
  background-color: red; } 

In the mixin directives we write, it is best to only define descendant selectors, so that they can be safely imported anywhere in the file.

  • A compound directive can refer to other compound directives:
@mixin compound {
  @include highlighted-background;
  @include header-text;
}
@mixin highlighted-background { background-color: #fc0; }
@mixin header-text { font-size: 20px; } 

4.3 Parameters ( Arguments)

Parameters can be used to set variables for the style of mixed commands and assign values. When referencing and defining mixed instructions, the order of parameters should be one-to-one correspondence, and the parameters can be assigned default values.

// $width有默认值
@mixin sexy-border($color, $width: 1in) {
  // 注意这里得 border,是CSS命名空间
  border: {
    color: $color;
    width: $width;
    style: dashed;}
}
p { @include sexy-border(blue); }
h1 { @include sexy-border(blue, 2in); }
// 编译为
p {
  border-color: blue;
  border-width: 1in;
  border-style: dashed; }
h1 {
  border-color: blue;
  border-width: 2in;
  border-style: dashed; } 

In addition, there are two more important points about the parameters:

  • Keyword parameter ( Keyword Arguments): When Mixinpassing a parameter by reference, pass the value precisely by specifying the parameter keyword (parameter name).
p { @include sexy-border($color: blue); }
h1 { @include sexy-border($color: blue, $width: 2in); } 

Although writing is a bit cumbersome, it is easy to read and can be accurately assigned.

  • Parameter variable ( Variable Arguments): When you are not sure how many parameters the mixed command needs, you can use parameter variable at the end of the parameter ...to declare, and Sassthese parameters will be treated as a list of values.
@mixin box-shadow($shadows...) {
  -moz-box-shadow: $shadows;
  -webkit-box-shadow: $shadows;
  box-shadow: $shadows;
}
.shadows {
  @include box-shadow(0px 4px 5px #666, 2px 6px 10px #999);
}
// 编译为
.shadowed {
  -moz-box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
  -webkit-box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
  box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
} 

You can also use parameter variables when quoting:

@mixin colors($text, $background, $border) {
  color: $text;
  background-color: $background;
  border-color: $border;
}
$values: #ff0000, #00ff00, #0000ff;
.primary {
  @include colors($values...);
}
// 编译为
.primary {
  color: #ff0000;
  background-color: #00ff00;
  border-color: #0000ff;
} 

4.4 Import content into the mixed command @content( Passing Content Blocks to a Mixin)

When citing Mixin, especially when citing at the outermost layer of the file, you can use @contentplaceholders, and then @includeimport the following content into @contentthe position, similar to templates, slots, etc.

@mixin apply-to-ie6-only {* html {
    @content;}
}
@include apply-to-ie6-only {
  #logo {
    background-image: url(/logo.gif);}
}
// 编译为
* html #logo {
  background-image: url(/logo.gif);
} 

Due to its frequent use Mixinin Sassstyle libraries. In order to simplify the use, it can be =expressed @mixinby, and +expressed by @include.

// Sass (这里就是Sass格式的语法了,而非SCSS格式)
=apply-to-ie6-only* html
    @content
+apply-to-ie6-only
  #logo
    background-image: url(/logo.gif) 
  • Block-level content and variable scope : By @contentimporting block-level content, its scope is associated with the context where it is defined, and has nothing to do with the scope inside the mixed instruction.
$color: white;
@mixin colors($color: blue) {
  background-color: $color;
  // @content 的内容的作用域在定义它的地方
  @content;
  border-color: $color;
}
.colors {
  @include colors { // 这里的color,虽然会被插入到@content的位置// 但是它的作用域是在定义它的地方,
    // 而定义它的地方,$color是全局变量,值为whitecolor: $color; }
}
// 编译为
.colors {
  background-color: blue;
  color: white;
  border-color: blue;
} 

Note that not every definition is in the global scope, and it is also possible that the definition is nested in a selector, and then the scope is the local scope of the selector.

5. Function instruction ( Function Directives)

SassAllows for custom functions, functions can be used in any attribute value or SassScript. Custom function names can be prefixed to avoid naming conflicts.

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

6. Output format

6.1:nested

Nested ( :nested) is sassthe default output format of , which clearly reflects the CSSrelationship HTMLbetween and . Selectors and attributes occupy a separate line, and the indentation is sassconsistent with that in the file, relying on indentation to reflect the nesting level.

// 编译后输出的CSS文件
#main {
  color: #fff;
  background-color: #000; }
  #main p {
    width: 10em; } 

6.2:expanded

The expand ( :expanded) format is the same as when writing by hand, and the selector is not indented.

#main {
  color: #fff;
  background-color: #000;
}
#main p {
  width: 10em;
} 

6.3:compact

The compact format ( Compact) takes up less space, each CSSrule occupies only one line, nested selectors do not leave blank lines, and non-nested selectors leave blank lines between them.

#main { color: #fff; background-color: #000; }
#main p { width: 10em; }
.huge { font-size: 10em; font-weight: bold; text-decoration: underline; } 

6.4:compressed

The compressed format ( Compressed) does not leave blank lines, spaces, comments, etc., and the output volume is the smallest.

#main{color:#fff;background-color:#000}#main p{width:10em}.huge{font-size:10em;font-weight:bold;text-decoration:underline} 

At last

A front-end information package is prepared for everyone. Contains 54, 2.57G front-end related e-books, "Front-end Interview Collection (with answers and analysis)", difficult and key knowledge video tutorials (full set).



Friends in need, you can click the card below to receive and share for free

Guess you like

Origin blog.csdn.net/web22050702/article/details/128664031