I. Introduction to SASS
Sass preprocessor is an auxiliary tool to enhance CSS. It adds advanced functions such as variables, nested rules, mixins, inline imports and so on on the basis of CSS syntax. These extensions make CSS more powerful and elegant. — Official Introduction
- Fully compatible with CSS3
- Add variables, nesting, mixins, and more to CSS
- Color and attribute values are computed by functions
- Provide advanced functions such as control directives
- Customize the output format
1. The relationship between SCSS and SASS
- Sass and SCSS are actually CSS preprocessing languages with different syntax formats.
- SCSS is the new syntax introduced by Sass3, and Sass is the syntax of the previous version of Sass3
- Either format can be imported (@import) directly for use in another format, or converted to another format by the sass-convert command line tool
- After SASS, the writing specification of SCSS is basically the same as that of CSS. In the era of SASS, there are strict indentation specifications and no ‘{}’ and ‘; Etc.
sass
Sass is the earliest sASS syntax format, known as the indent format (Indented sass), often shortened to “sass”, is a simplified format. It uses indentation instead of curly braces to indicate that properties belong to a selector, and “newline” instead of a semicolon to separate properties, which many find easier to read and faster to write than SCSS. The indent format can also use the full functionality of Sass, with the exception of different expressions in individual places compared to SCSS
scss
SCSS is a new syntax introduced by Sass 3. Its syntax is fully compatible with CSS3 and inherits the powerful functions of Sass. That is, any standard CSS3 style sheet is a valid SCSS file with the same semantics. SCSS requires semicolons and curly braces instead of line breaks and indentation. SCSS is insensitive to whitespace and, like cSS3 syntax, the suffix can be.scss and.sass
SCSS is written the same as CSS. You can still use your existing “.css “file by modifying it to”.scss “.
Background-color: #faa // SCSS #root {width: 30%; background-color: #faa; }Copy the code
Therefore, it is recommended to use SCSS. The following content is in SCSS syntax format
2. Common preprocessors of the CSS
1. SCSS/SASS
SASS (SCSS). Born in 2007, the earliest and most mature CSS preprocessor, with the support of the Ruby community and compass, the most powerful CSS framework, has evolved to fully CSS compatible SCSS under the influence of LESS. The file ends with.sass
2. LESS
LESS (LESS). Born in 2009, SASS draws on the strengths of SASS and is compatible with CSS syntax, which makes it more convenient for developers to use. However, compared with SASS, its programming functions are not rich enough, which makes SASS evolve into SCSS.
3. Stylus
Stylus (. Styl). Was born in 2010, from the Node.js community, mainly used for Node project CSS preprocessing support, popularity is lower than the first two.
Second, environment configuration
Less, SCSS (SASS), and stylus codes are not parsed directly by browsers, so you must compile them into CSS code first
1, the installation
The simple and practical way to set up the environment is to use VSCode to install extensions for two Easy Sass (compilation) and Sass (code hints).
2, the configuration
Go to settings.json global configuration file in Settings and add the following
"Easysass.com pileAfterSave" : true, / / save SCSS/sass files automatically compile/after/compile different formats of CSS "easysass. Formats" : [{" format ": "expanded", "extension": ".css" }, { "format": "compressed", "extension": ".min.css"}], //1, format Optional parameter // Parameter value Expanded (unindent, extended CSS code) // compact: concise CSS code with all styles of each selector on the same line. // compressed: Compressed CSS code. // 2. Easysas.formats [I].extension sets the file extension name for the compiled output, where you can customize the file name, and the output CSS file name is generated in the format of "current Sass file name (without the extension name) + custom file name here" // for example: Set ".min. CSS ", assuming the current Sass file is style. SCSS, the compiled output CSS file is style.min. CSS "easysass.targetdir ": "// In most cases, SCSS /sass files and CSS files are not in the same directory. By default, Easy Sass outputs CSS files in the same directory as the current Sass fileCopy the code
Test: create an A.s. CSS file, write some styles, save and two files will be compiled automatically
-----text
|
--a.scss
|
--a.css
|
--a.min.css
Copy the code
Third, core grammar
1, the variable
[1] Variable declaration
$width: 1600px; $pen-size: 3em;Copy the code
[2] Use variables
A variable is called by its name
#app {
height: $width;
font-size: $pen-size;
}
Copy the code
[3] scope
Variables defined inside the style default text local variables, can only be used internally, converting local variables to global variables can be added! Global declarations
#foo { $width: 5em ! global; width: $width; } #bar { width: $width; }Copy the code
The compiled:
#foo {
width: 5em;
}
#bar {
width: 5em;
}
Copy the code
Underlining is also recommended
2. Data types
SassScript supports six main data types:
- Numbers,
1, 2, 13, 10px
- String, quoted string and unquoted string,
"foo", 'bar', baz
- The color,
Blue, # 4 a3f9, rgba (255,0,0,0.5)
- The Boolean,
true, false
- A null value,
null
- Array (list), delimited by Spaces or commas,
1.5 EM 1EM 0 2EM, Helvetica, Arial, Sans-serif
- Maps, the equivalent of JavaScript object,
(key1: value1, key2: value2)
SassScript also supports other CSS property values, such as Unicode character sets, or! Important statement. However, Sass does not treat these attribute values differently and treats them as unquoted strings.
Type -of($value)
[1]. Strings
SassScript supports two string types of CSS: quoted strings and unquoted strings.
$name: 'Tom Bob'; $container: "top bottom"; $what: heart; // Note: CSS files do not change their types when compiled. With the exception of '#{}' (Interpolation), the quoted string will be compiled to an unquoted string to make it easier to reference the selector name in mixinsCopy the code
[2], a Null value (Null)
There is only one value, null
$value: null; // Note: Since it represents null, you cannot use it to perform arithmetic operations on any typeCopy the code
[3], Booleans
There are only two values: true and false
$a: true; $b: false; // Note: False is returned only if it is false and null, and true is returned for everything elseCopy the code
[4]. Array (Lists)
A series of values separated by Spaces or commas. In fact, individual values are also considered arrays — groups containing only one value. The index starts at 1
$list0: 1px 2px 5px 6px; $list1: 1px 2px, 5px 6px; $list2: (1px 2px) (5px 6px); // The array contains two subarrays (separated by parentheses)Copy the code
When an array is compiled to CSS, Sass does not add any parentheses (CSS does not do this), so (1px 2px) (5px 6px) is exactly the same as 1px 2px, 5px 6px in the compiled CSS file. But they have different meanings in Sass files, where the former is an array of two arrays and the latter is an array of four values.
Use () to represent an empty array that does not contain any values (a map that is also considered empty after Sass 3.3). Font-family: arial, sans-serif (); font-family: arial, sans-serif (); If the array contains empty arrays or empty values, they will be cleared at compile time, such as 1px 2px () 3px or 1px 2px null 3px.
Comma-delimited arrays allow the ending comma to remain, which emphasizes the structural relationship of arrays, especially if you need to declare arrays that contain only a single value. For example, (1,) represents an array that contains only 1, while (1, 2, 3,) represents an array that contains the space-separated arrays 1, 2, 3.
[5].Maps
Maps must be surrounded by parentheses and can map any type of key-value pair (any type, including inline Maps, though this is not recommended)
$map: (
$key1: value1,
$key2: value2,
$key3: value3
)
Copy the code
[6]. The color (Colors)
CSS original color types, hexadecimal, RGB, RGBA, HSL, HSLA and color words
SCSS provides a built-in Colors function to make it easier to use Colors
$color0: green; $color1: lighten($color, 15%); $color2: darken($color, 15%); $color3: saturate($color, 15%); $color4: desaturate($color, 15%); $color5: (green + red); $color6: RGB (# f3e1e1, 0.3); RGB plus transparency cannot be written in CSS like this, it will be converted to RGB after compilationCopy the code
3, the operation
All data types support equality == or! =, in addition, each data type also has its own supported operations.
[1], number operation
SassScript supports addition, subtraction, multiplication, division, and rounding of numbers (+, -, *, /, %), converting values between units if necessary
If you want to preserve operation symbols, you should use interpolation syntax
-
+
$add1: 1 + 2; // 3 $add2: 1 + 2px; // 3px $add3: 1px + 2; // 3px $add4: 1px + 2px; $add5: "a" + "b"; // "ab" $add6: "a" + b; // "ab" $add7: a + "b"; // ab $add8: a + b; // ab // number and string $add9:1 + a; // 1a $adda: a + 1; // a1 $addb: "1" + a; // "1a" $addc: 1 + "a"; // "1a" $addd: "a" + 1; // "a1" $adde: a + "1"; // a1 $addf: 1 + "1"; / / "11"Copy the code
B. Pure string: The first string is marked with or without quotation marks. C Number and string: the first string is marked with quotation marks, the result must be marked with quotation marks. If the first digit is not a number and the last digit has a quotation mark ("), the result must be quotedCopy the code
-
-
$add1: 1 - 2; // -1 $add2: 1 - 2px; // -1px $add3: 1px - 2; // -1px $add4: 1px - 2px; //-1px $sub1: a - 1; // a-1 $sub2: 1 - a; // 1-a $sub3: "a" - 1; // "a"-1 $sub4: a - "1"; // a-"1"Copy the code
// Summary: Each field must be preceded by a number, and only one of the two fields must be followed by a character (because the suffix is treated as a unit). As long as one of the values does not start with a number, the results are concatenated with Spaces removed in orderCopy the code
-
*
$num1: 1 * 2; // 2 $mul2: 1 * 2px; // 2px $num3: 1px * 2; // 2px $num4: 2px * 2px; $num5:1 * 2abc; // 2abcCopy the code
// Summary: Each field must be preceded by a number, and only one of the two fields must be followed by a character (because the suffix is treated as a unit). Other compilations failCopy the code
-
/
// Summary: a. will not be rounded, accurate to 5 decimal places b. each field must be preceded by a number, and the former is a simple number without a unit, the latter (divisor) must not have a character. The rest of the results are concatenated by removing Spaces in order. (because suffixes are now treated as units)Copy the code
-
%
// Summary: a. there must be a space between the value and "%", otherwise it will be treated as a stringCopy the code
[2], relational operators
With JavaScript…
[3]. Boolean operators
SassScript supports Boolean and or and not operations.
[4], color value operation (not commonly used)
The calculation of the color values is performed in segments, that is, the red, green, and blue values are computed separately:
p {
color: #010203 + #040506;
}
Copy the code
Calculate 01 + 04 = 05 02 + 05 = 07 03 + 06 = 09 and compile to
p {
color: #050709; }
Copy the code
Using color functions is more convenient than calculating color values.
Arithmetical operations can also be performed between numbers and color values, again piecewise, for example
p {
color: #010203 * 2;
}
Copy the code
Calculate 01 * 2 = 02 02 * 2 = 04 03 * 2 = 06 and compile to
p {
color: #020406; }
Copy the code
Note that if the color values contain alpha channels (both RGBA or HSLA color values), they must have equal alpha values in order to perform operations, since arithmetic operations do not apply to alpha values.
P {color: rgba(255, 0, 0, 0.75) + rgba(0, 255, 0, 0.75); }Copy the code
Compiled into
P {color: rgba(255, 255, 0, 0.75); }Copy the code
The color value of the alpha channel can be adjusted by the opacify or Transparentize functions.
$always red: rgba(255, 0, 0, 0.5); P {color: opacify($always -red, 0.3); Background - color: transparentize ($translucent - red, 0.25); }Copy the code
Compiled into
P {color: rgba(255, 0, 0, 0.8); Background: rgba(255, 0, 0, 0.25); }Copy the code
IE filters require that all color values contain an alpha layer and the format must be fixed at #AABBCCDD. Using the ie_hex_str function, you can easily convert the color to the format required by IE filters.
$always red: rgba(255, 0, 0, 0.5); $green: #00ff00; div { filter: progid:DXImageTransform.Microsoft.gradient(enabled='false', startColorstr='#{ie-hex-str($green)}', endColorstr='#{ie-hex-str($translucent-red)}'); }Copy the code
Compiled into
div {
filter: progid:DXImageTransform.Microsoft.gradient(enabled='false', startColorstr=#FF00FF00, endColorstr=#80FF0000);
}
Copy the code
[5], Parentheses
Parentheses can be used to influence the precedence of an operation:
p {
width: 1em + (2em * 3);
}
Copy the code
Compiled into
p {
width: 7em; }
Copy the code
Addendum: operation priority is the same as js
[6], string operation
+ can be used to concatenate strings
p {
cursor: e + -resize;
}
Copy the code
Compiled into
p {
cursor: e-resize; }
Copy the code
Note that if a quoted string (to the left of +) concatenates an unquoted string, the result of the operation is quoted, whereas an unquoted string (to the left of +) concatenates a quoted string, the result of the operation is unquoted.
p:before {
content: "Foo " + Bar;
font-family: sans- + "serif";
}
Copy the code
Compiled into
p:before {
content: "Foo Bar";
font-family: sans-serif; }
Copy the code
When an expression is used with other values, use a space as a concatenation:
p {
margin: 3px + 4px auto;
}
Copy the code
Compiled into
p {
margin: 7px auto; }
Copy the code
Use #{} interpolation statements to add dynamic values to quoted text strings:
p:before { content: "I ate #{5 + 10} pies!" ; }Copy the code
Compiled into
p:before { content: "I ate 15 pies!" ; }Copy the code
An empty value is treated as inserting an empty string:
$value: null; p:before { content: "I ate #{$value} pies!" ; }Copy the code
Compiled into
p:before { content: "I ate pies!" ; }Copy the code
4. Nested rules (common)
Sass writing styles can be nested in the same way as DOM writing
The < body > < div id = "app" > < span > ha ha ha ha < / span > < div class = "front" > < a href = "#" > < / a > < / div > < / div > < / body >Copy the code
#app { span { color:red; } .front { a { margin:0; padding:0; } #app aside{.... }// This is also ok}}Copy the code
#app span {
color: red;
}
#app .front a {
margin: 0;
padding: 0;
}
Copy the code
[1], the identifier of the parent selector &
In general, sass unlocks a nested rule by concatenating the parent selector (#app) to the front of the child selector (span and.font a) with a space (#content span and # Content front a). This is called a descendant selector in CSS because it selects all elements in the element with the ID app that hit the span and.front a selectors. But there are some cases where you don’t want Sass to generate this connection using descendant selectors.
One of the most common cases is when you write a pseudo-class called hover for an element like a link, and you don’t want to connect as a descendant selector.
article a {
color: blue;
:hover { color: red }
}
Copy the code
SCSS undoes the nested rules and the code above will not compile. Because pseudo-class selectors do not have Spaces between selected elements, they do when unpacked using SCCS nesting rules.
/* article a:hover {color: red; /* article a:hover {color: red; }Copy the code
This means that the color: red rule will be applied to the article A :hover selector, and all children linked within the article element will turn red when hover is used. This is not true! You want to apply this rule to hyperlinks themselves, and descendant selectors don’t do it for you.
So to solve this problem, the & identifier appears. With the ampersand identifier, when using nested rules, the parent selector provides better control over how nested rules are unwrapped. Can the ampersand be placed wherever the selector can be found
article a {
color: blue;
&:hover { color: red }
}
Copy the code
When a nested rule containing the parent selector identifier is turned on, it is not concatenated like a descendant selector, but instead is replaced directly by the parent selector:
article a { color: blue }
article a:hover { color: red }
Copy the code
This is useful when adding pseudo-classes such as: hover to parent selectors.
There is also another way to use the parent selector identifier. You can add a selector before the parent selector. For example, when the user is using Internet Explorer, you would add an Internet Explorer class name to the tag via JavaScript, and write a special style for this case:
#content aside { color: red; Body. Ie & {color: green}} */ #content {color: red}; body.ie #content aside { color: green }Copy the code
Sass is very smart about selector nesting, even with a parent selector. Sass also handles this nesting perfectly when it comes to group selectors (formed by multiple comma-separated selectors)
[2], nesting of group selectors
Group of selectors
.button, button { margin: 0; } Group selector rules apply to elements that hit any of the group selectorsCopy the code
Problems arising
Repetitive work increases as follows
.container h1, .container h2, .container h3 { margin-bottom: .8em }
Copy the code
SCSS solution
.container {h1, h2, h3 {margin-bottom:.8em}Copy the code
More examples of different situations
Nav, aside {a {color: blue}}Copy the code
The ability to handle this nesting of group selector rules is one of SASS’s contributions to reducing duplicate typing. Especially when the nesting level is two or even three levels higher, writing a group selector once is much less work than normal CSS writing.
There are pros and cons, and you need to pay special attention to the nested CSS generated by group selectors. While sass makes your stylesheets look small, the actual CSS generated can be very large, which slows down your site.
[3], subcombinatorial selectors and same-level combinatorial selectors: >, +, and ~;
On the last aspect of selector nesting, let’s look at how Sass handles combinatorial selectors, such as the use of >, +, and ~. As you’ll see, you don’t even need to use the parent selector identifier in this scenario.
Subcombination selector: “>”
article section { margin: 5px }
article > section { border: 1px solid #ccc }
Copy the code
You can select the direct children of an element using subcombination selector >. In the above example, the first selector selects all elements under article that hit the section selector. The second selector selects only the elements that match the Section selector in the child element immediately following the article.
In fact, it is the same as CSS child selector rules
Adjacent combination selector: “+”
In the following example, you can select the p element immediately following the header element with the layer adjacent combinatorial selector + :
Header + p {font-size: 1.1em} /* The paragraph immediately following the image is selected */ img + p {font-size: 1.1em}; }Copy the code
Group selector “~”
You can also select all article elements of the same level after an article, regardless of how many other elements are separated between them, using the same-level collective selector ~ :
article ~ article { border-top: 1px dashed #ccc }
Copy the code
Comprehensive instance
article {
~ article { border-top: 1px dashed #ccc }
> section { background: #eee }
dl > {
dt { color: #333 }
dd { color: #555 }
}
nav + & { margin-top: 0 }
}
Copy the code
Sass will untangle and assemble these nested rules as you wish:
article ~ article { border-top: 1px dashed #ccc }
article > footer { background: #eee }
article dl > dt { color: #333 }
article dl > dd { color: #555 }
nav + article { margin-top: 0 }
Copy the code
[4], nested attributes
In SASS, in addition to CSS selectors, properties can also be nested.
The rules for nested attributes are as follows: break the attribute name from the underscore -, add a colon: after the root attribute, and then a {} block in which the child attribute portion is written. Just like CSS selectors nested, sass unwinds your sub-attributes one by one, connecting the root and sub-attributes with a underlined -, resulting in the same CSS style that you would manually write over and over again:
Nav {border: {// Different from nested selectors style: solid; width: 1px; color: #ccc; }} nav {border-style: solid; border-width: 1px; border-color: #ccc; }Copy the code
For attribute abbreviations, you can even nest exceptions like the following:
nav { border: 1px solid #ccc { left: 0px; right: 0px; }}Copy the code
This is better than the equivalent:
nav {
border: 1px solid #ccc;
border-left: 0px;
border-right: 0px;
}
Copy the code
Nesting of properties and selectors is a great feature because not only do they greatly reduce the amount of writing you do, but they also make the style structure of your writing clearer and easier to read and develop through visual indentation.
5. Other common grammar
[1]
- Sass supports standard CSS multi-line comments
/ * * /
, and single-line comments//
, the former is fully output to the compiled CSS file, while the latter is not. - will
!
The first character of a multi-line comment indicates that the comment is retained in compressed output mode and output to a CSS file, often used to add copyright information. (General use) - Interpolation statement can also be written into multi-line comments to output variable values
Such as:
/* hello world! */ // compile scss files to css // it's ready to do it. $pink: #f3e1e1; html{ background-color: $pink; } $author: '[email protected]'; / *! Author: #{$author}. */Copy the code
After compiling in development mode:
/* hello world! */ html{ background-color: #f3e1e1; } / *! Author: '[email protected]'. */Copy the code
Min mode output mode after compilation:
html{ background-color: #f3e1e1; } / *! Author: '[email protected]'. */Copy the code
[2], Interpolation grammar (emphasis)
Variables can be used in selectors, attribute names, and attribute values through the #{} interpolation statement. Like ${} in js
In most cases, though, using attribute values like this is probably not as convenient as using variables directly, but using #{} can avoid Sass running operational expressions and compile CSS directly.
$n:front;
#app .#{$n} {
color:red;
}
Copy the code
#app .front {
color: red;
}
Copy the code
$name: foo; $attr: border; p.#{$name} { #{$attr}-color: $name; } // after compile: p.foo {border-color: foo; }Copy the code
[3].! default
Can be added at the end of a variable! Default gives a fail! Default declares that the assigned variable is assigned. If the variable has already been assigned, it will not be reassigned, but if the variable has not been assigned, it will be assigned a new value.
$content: "First content"; $content: "Second content?" ! default; $new_content: "First time reference" ! default; #main { content: $content; new-content: $new_content; } // compile to: #main {content: "First content"; new-content: "First time reference"; }Copy the code
Note: variables that are null are treated as if they are not! The default value.
[4].! global
Promoting local variables to global variables (scope)
6. @-Rules and Instructions (emphasis)
Sass supports all CSS3@-Rules and the SPECIFIC Sass “Directives”
[1]@import
css
There is a particularly uncommon feature, namely@import
Rule, it is allowed in acss
Import other filescss
File. However, the consequence is only implementation@import
“, the browser will download the othercss
File, which causes the page to load very slowly.sass
There is also a@import
Rules, but the difference is,sass
the@import
Rules are being generatedcss
Import the relevant files into the file. This means that all related styles are grouped into onecss
File without making additional download requests. In addition, all variables and mixers defined in the imported file are available in the imported file.- use
sass
the@import
Rules do not need to specify the full name of the file being imported. You can omit.sass
or.scss
File suffixes (see figure below).
For example: @ import “sidebar”; This command adds all styles from the sidebar. SCSS file to the current stylesheet.
Import Format Requirements
The following common do not meet
- The file extension is
.css
; - File name to
http://
At the beginning. - File name is
url()
; @import
Contains media queries
@import "foo.scss"; @import "foo"; @import "foo.css"; @import "foo" screen; @import "http://foo.com/bar"; @import url(foo);Copy the code
Sass allows multiple files to be imported at the same time, for example, just-corners and text-shadow files:
@import "rounded-corners", "text-shadow";
Copy the code
Import files can also use #{} interpolation statements, but instead of using variables to dynamically import Sass files, it only works with CSS URL () imports:
$family: unquote("Droid+Sans"); @import url("http://fonts.googleapis.com/css?family=#{$family}"); / / compiled to: @ import url (" http://fonts.googleapis.com/css?family=Droid+Sans ");Copy the code
Use SASS partial files
If you have an SCSS or Sass file that needs to be imported, but you don’t want it to be compiled as a CSS file, you can put an underscore in front of the file name to avoid being compiled. This will tell Sass not to compile it into a CSS file. You can then import the file as usual, omitting the underline before the filename.
For example, naming the file _colors.scss will not compile the _colours.css file.
@import "colors";
Copy the code
In the above example, the file imported is actually _colors.scss
Note that underlined and ununderlined files of the same name cannot exist at the same time. Underlined files will be ignored.
Nested @ import
In addition to this, nesting @import is supported, but not in mixin or Control directives. Directives
In most cases, @import is usually used at the outermost layer of the file (outside of the nesting rules). In fact, @import can also be nested within CSS styles or @media, which has the same effect as normal usage, except that the imported styles can only appear in the nested layer.
Suppose the example.scss file contains the following styles:
.example {
color: red;
}
Copy the code
Then import it into the #main style
#main {
@import "example";
}
Copy the code
Will be compiled to
#main .example {
color: red;
}
Copy the code
[2].@media
The @media directive in Sass is used the same way as in CSS, with the added feature of allowing it to be nested within CSS rules. If @Media is nested within CSS rules, at compile time, @Media will be compiled to the outermost layer of the file, containing the nested parent selector. This feature makes @Media easier to use without having to reuse selectors and disrupt the CSS writing process.
.sidebar { width: 300px; @media screen and (orientation: landscape) { width: 500px; } // compile to.sidebar {width: 300px; @media screen and (orientation: landscape) { width: 500px; }}Copy the code
@media queries can be nested with each other. Sass automatically adds and when compiling
@media screen { .sidebar { @media (orientation: landscape) { width: 500px; @media screen and (orientation: landscape) {. Sidebar {width: 500px; }}Copy the code
@media can even use SassScript (such as variables, functions, and operators) instead of condition names or values
$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; }}Copy the code
[3].@extend
@extend is inheritance. It’s common when designing a web page that one element uses exactly the same style as another, but adds an extra style.
You typically define two classes for elements in HTML, one generic style and one special style. Suppose you wanted to design a normal error style and a severe error style, it would look like this:
<div class="error seriousError">
Oh no! You've been hacked!
</div>
Copy the code
A. Basic inheritance
.error { border: 1px #f00; background-color: #fdd; } .seriousError { @extend .error; border-width: 3px; SeriousError; border-width: 3px; border-width: 3px; SeriousError is styled separately so that.seriouserror is not used where.seriouserror is used.Copy the code
Extend extends a repeated style (.error) to a special style (.seriouserror) that needs to include the style.
Other styles that use.error will also be inherited to.seriouserror. For example, another.error. Intrusion style uses hack.png as the background.
.error.intrusion {
background-image: url("/image/hacked.png");
}
Copy the code
Be aware of the following:
.error {
border: 1px #f00;
background-color: #fdd;
}
.error.intrusion {
background-image: url("/image/hacked.png");
}
.seriousError {
@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; }
Copy the code
When merger selector, @ the extend will be very cleverly avoid needless repetition, the.seriouserror..seriouserror will be compiled into..seriouserror, cannot match any element selector will be deleted.
B. Inherit complex selectors
Class selectors are not the only ones that can be extended. Sass allows extending any selector defined for a single element, such as.special. Cool, a:hover, or a.user[href^=”http://”]
C. Multiple inheritance
The same selector can be extended to multiple selectors, and the properties it contains will be extended to all extended selectors
D. Multi-level inheritance
After one selector is extended to a second, you can continue to extend the second selector to a third
E. Selector column (not recommended)
It is currently not possible to extend Selector columns, such as.foo. bar or.foo +.bar, to other elements, but it is possible to extend other elements to Selector columns.
Try not to use merge selector columns, because permutations and combinations can occur if you follow personal reasoning, so the SASS compiler only keeps useful combinations, but permutations and combinations can still exist, which can be potentially dangerous.
-
When two columns are merged, if they do not contain the same selector, two new selectors are generated: the first listing now precedes the second column, or the second listing now precedes the first column
#admin .tabbar a { font-weight: bold; } #demo .overview .fakelink { @extend a; } // Compile to: #admin .tabbar a, #admin .tabbar #demo .overview .fakelink, #demo .overview #admin .tabbar .fakelink { font-weight: bold; }Copy the code
-
If two columns contain the same selector, the same portion will be merged and the rest will be output alternately
#admin .tabbar a { font-weight: bold; } #admin .overview .fakelink { @extend a; } // compile to # admin.tabbar a, # admin.tabbar.overview.fakelink, # admin.overview.tabbar.fakelink {font-weight: bold; }Copy the code
F. Extend in directives There are some limitations when using @extend in directives (as in @media) : Sass cannot extend CSS rules outside the @media layer to CSS inside the directive layer.
G. %placeholder is a selector placeholder, used in conjunction with the @extend-only selector.
Effect: Only styles are defined, but they do not apply to elements matched by the original selector
// example1: %img { color: red; } .path{ @extend %img; } // after compiling:.path {color: red; }Copy the code
// example2: #context a%extreme { color: blue; font-weight: bold; font-size: 2em; }.notice {@extend %extreme; } // Note: must be "." and "#" selectorsCopy the code
[4], uncommon instructions
Encounter learning series
A, @ the at – root
The @at-root directive causes one or more rules to be emitted at the root of the document, rather than being nested beneath their parent selectors. It can either be used with a single inline selector
原 文 : The @at root directive causes one or more rules to be issued at the root of a document, rather than nested under its parent selector. It can be used with a single inline selector
And @at-root causes multiple rules to jump out of nesting
@at-root does not make rules or selectors jump out of instructions by default. Use without and with to solve this problem
Understanding can
b.@debug
For debugging, output to the standard error output stream
$size: 9px;
.file{
@debug $size;
}
Copy the code
c,@warn
Used for warning, output as standard error output stream
d.@error
For error reporting, output by standard error output stream
The sequence | @-rules | role |
---|---|---|
1 | @import | Import sASS or SCSS files |
2 | @media | Use to set style rules to different media types |
3 | @extend | Share selectors by inheritance |
4 | @at-root | Go to the root node |
5 | @debug | For debugging, output to the standard error output stream |
6 | @warn | Used for warning, output as standard error output stream |
7 | @error | For error reporting, output by standard error output stream |
Control Directives
[1].if()
Ternary operator
If (expression, value1, value2)
p { color: if(1 + 1 == 2, green, yellow); } // compile () p{color: green; }Copy the code
[2].@if
Conditional statements
If the @if expression returns a value other than false or null, the condition is true and the code in {} is printed
You can have multiple @else if declarations, or you can have an @else declaration. If the @if declaration fails, Sass will execute the @else if declaration one by one, and if all fail, the @else declaration will be executed last
-
Single @ the if
p { @if 1 + 1 == 2 { color: red; } } // compile: p { color: red; } Copy the code
-
@if - @else
p { @if 1 + 1 ! = 2 { color: red; } @else { color: blue; } } // compile: p { color: blue; }Copy the code
-
@if - @else if - @else
$age: 19; p { @if $age == 18 { color: red; } @else if $age == 19 { color: blue; } @else { color: green; } } // compile: p { color: blue; } Copy the code
[3].@for
Two types of loop statements
@for $var from <start> through <end>
@for $var from <start> to <end>
Similarities and differences between through and to:
- Similarity: Values contained in both
- Differences: Values included through, but not to
@for $i from 1 through 3 {
.item-#{$i} { width: 2em * $i; }
}
// compile:
.item-1 {
width: 2em; }
.item-2 {
width: 4em; }
.item-3 {
width: 6em; }
Copy the code
[4].@while
Looping statements
Expression: @while expression
The @while directive repeats the output format until the expression returns false. This allows for a more complex loop than @for, but is rarely used
$i: 6;
@while $i > 0 {
.item-#{$i} { width: 2em * $i; }
$i: $i - 2;
}
// compile:
.item-6 {
width: 12em; }
.item-4 {
width: 8em; }
.item-2 {
width: 4em; }
Copy the code
[5].@each
Looping statements
$var in $vars
$var can be any variable name
$vars Can only be Lists or Maps
-
A one-dimensional list
@each $animal in puma, sea-slug, egret, salamander { .#{$animal}-icon { background-image: url('/images/#{$animal}.png'); } } // compile: .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'); } Copy the code
-
2 d list
@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; } } // compile: .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; } Copy the code
-
maps
@each $header, $size in (h1: 2em, h2: 1.5em, h3: 1.2em) {#{$header} {font-size: $size; } } // compile: h1 { font-size: 2em; } h2 {font-size: 1.5em; } h3 {font-size: 1.2em; }Copy the code
8. Mixin @mixin (emphasis)
If you have a few small similarities (consistent colors and fonts, for example) throughout your site, using variables to handle the situation uniformly is a good idea. But as your styles get more complex and you need to reuse large chunks of style code, individual variables can’t handle this. You can achieve bulk style reuse with sASS mixers.
[^] Note: This is not a function! No return value!!
[1]. Define the mixer
The use of the mixin directive is to add the name and style, and optional parameters, after the @mixin directive.
// Format: @mixin name {// style.... }Copy the code
// example: @mixin large-text {font: {family: Arial; size: 20px; weight: bold; } color: #ff0000; }Copy the code
[2]. Reference hybrid style @include
Use the @include directive to refer to the blended style in the form of a blended name followed by the desired parameters (optional).
// format: @include name; // Note: When there are no parameters or both parameters have default values, parentheses and no parentheses can be usedCopy the code
// example: p {include large-text; } // compile: p { font-family: Arial; font-size: 20px; font-weight: bold; color: #ff0000; }Copy the code
[3]. The parameters
Format: Write parameters in parentheses after Mixin names in the format of variables, separated by commas
Default values are supported. Support for multiple parameters; Support for indefinite parameters; Supports location and keyword transmission
A. Location parameter transmission
@mixin mp($width) {
margin: $width;
}
body {
@include mp(300px);
}
Copy the code
B. Keyword parameter transmission
@mixin mp($width) {
margin: $width;
}
body {
@include mp($width: 300px);
}
Copy the code
C. Parameter Default values
@mixin mp($width: 500px) {
margin: $width;
}
body {
@include mp($width: 300px);
// or
@include mp(300px);
}
Copy the code
D. Indefinite parameters
Official: Variable Arguments
原 文 : Parameter variables
Sometimes, it is not clear how many parameters a mixed instruction needs to use. In this case, you can use parameter variables… The declaration (written at the end of the argument) tells Sass to treat these arguments as a list of values
@mixin mar($value...) {
margin: $value;
}
Copy the code
[4]. Import content into blended styles
When referring to a blended style, you can import a piece of code into the blended instruction before printing the blended style, and the extra imported portion will appear in the @Content flag
Think of it as an upgraded version of parameters
@mixin example {
html {
@content;
}
}
@include example{
background-color: red;
.logo {
width: 600px;
}
}
// compile:
html {
background-color: red;
}
html .logo {
width: 600px;
}
Copy the code
9. function instructions
[1]. Built-in functions (reference)
A. String functions
The first index is 1 and the last index is -1; Both sides of the slice are closed intervals
Function name and parameter type | Function are |
---|---|
quote($string) | Add quotation marks |
unquote($string) | Remove the quotes |
to-lower-case($string) | A lower case |
to-upper-case($string) | Into the capital |
str-length($string) | Return the length of $string. |
str-index( substring) |
return The location of the string |
str-insert( insert, $index) |
in Insert $insert at index |
str-slice( Start – at $end – at) |
The interception A string between start-at and $end-at |
B. Numerical functions
Function name and parameter type | Function are |
---|---|
percentage($number) | Convert to a percentage |
round($number) | Round to an integer |
ceil($number) | The value is rounded up |
floor($number) | The value is rounded down |
abs($number) | Get absolute value |
min($number…) | Get the minimum |
max($number…) | Get maximum value |
random($number? :number) | Pass no value: get 0-1 random number; Passing in a positive integer n: Get a random integer from 0 to n (left open and right closed) |
C. Array functions
Function name and parameter type | Function are |
---|---|
length($list) | Get the array length |
nth($list, n) | Gets the element with the specified subscript |
set-nth( n, $value) |
to Insert $value at n |
join( list2, $separator) |
Joining together Separator is the separator of the new list. By default, it is auto. Separator can be used as comma or space |
append( val, $separator) |
to Val. $separator is the separator of the new list. By default, it is auto. Select comma or space |
index( value) |
return The index value in list |
Zip ($lists…). | Combine several lists into a multidimensional list; Each list must have the same number of values |
D. Mapping function
Function name and parameter type | Function are |
---|---|
map-get( key) |
To obtain Key corresponds to $value |
map-merge( map2) |
merge Map2, returns a new $map |
map-remove( key) |
from Key returns a new $map |
map-keys($map) | return key |
map-values($map) | return value |
map-has-key( key) |
judge Key, returns the corresponding Boolean value |
keywords($args) | Returns a function parameter whose value can be modified dynamically |
E. Color function
-
RGB function
Function name and parameter type Function are rgb(
green, $blue)Returns a hex color value rgba(
green,
alpha)Return an RGBA;
Green and $blue can be passed together as a color word, HSL, RGB, or hexadecimalred($color) Get the red value from $color green($color) Get the green value from $color blue($color) Get the blue value from $color mix(
color2,$weight?)In accordance with the
Color1 and $color2 mix into a new color -
An HSL function
Function name and parameter type Function are hsl(
saturation,$lightness)A color is created from the values of hue, saturation, and lightness hsla(
saturation,
alpha)A color is created from the values of hue, saturation, lightness and alpha saturation($color) Saturation values are obtained from a color lightness($color) Gets the lightness value from a color adjust-hue(
degrees)Create a new color by changing the hue value of a color lighten(
amount)Create a new color by changing the brightness value of the color to make it lighter darken(
amount)Darken the color by changing the brightness value of the color to create a new color hue($color) Gets the brightness hue value from a color -
Opacity function
alpha(
color)Gets the color transparency value rgba(
alpha)Change the opacity of the color opacify(
amount) / fade-in(
amount)Make the color more opaque transparentize(
amount) / fade-out(
amount)Make the color more transparent
F. Introspection function
Function name and parameter type | Function are |
---|---|
type-of($value) | Returns the type of $value |
unit($number) | Returns the unit of $number |
unitless($number) | $number = $number |
comparable( number2) |
judge Number2 Specifies whether to add, subtract, and merge, and returns the corresponding Boolean value |
[2]. Custom functions (emphasis)
Sass supports custom functions and can be used in any attribute value or Sass script:
Basic format:
@function fn-name($params...) { @return $params; } // Can pass parameters, can returnCopy the code
$grid-width: 40px;
$gutter-width: 10px;
@function grid-width($n) {
@return $n * $grid-width + ($n - 1) * $gutter-width;
}
#sidebar { width: grid-width(5); }
Copy the code
Compiled into
#sidebar {
width: 240px; }
Copy the code
As with mixins, several global variables can be passed to functions as arguments. A function can contain more than one statement that requires a @return call to output the result.
Custom functions can also use keyword arguments. The above example could also be written like this:
#sidebar { width: grid-width($n: 5); }
Copy the code
It is recommended to prefix custom functions to avoid naming conflicts. Others reading the code will also know that this is not a built-in feature of Sass or CSS.
Custom functions, like mixins, support variable arguments
Supplement:
Options for @extend, @mixin, and @function
According to the csswizardry.com/2016/02/mix…
Minxins have better performance over the network than @extend. Even though some files are larger uncompressed, using gzip ‘compression still ensures better performance.
So @extend we’ll try not to use, and the difference between @mixin and @function is in definition and usage
- Different definitions:
@function
You need to call@return
Output the result. @mixin doesn’t. - Different ways of use:
@mixin
use@include
References, and@function
The function is executed using parentheses.
Fourth, reference materials
Segmentfault.com/a/119000001…
www.sass.hk/
www.bilibili.com/video/BV1Zg…