Worry-free attention can learn more about the front-end tutorial. Questions or suggestions, please leave a message; If you feel free to help you, welcome to like [1024]
I. Overview of Sass
Today, let’s talk about Sass. I used less for a long time before. When I first touched it, I felt it was a magic object, but in comparison, Sass is more fragrant.
Writing CSS for a long time will naturally be able to find the shortcomings of CSS when writing, can not nest, no variables, more can not like JS with a cycle automatically generated and so on, these problems are all solved by less
Less adds variables, adds nesting, and a bunch of nice features that I won’t talk about here, but sass. In fact, WHEN I just contacted less, I knew there was sass. But at that time, Sass was very strange. The writing method was too novel
body
margin: 0
padding: 0
height: 20px
width: 30px.Copy the code
See that? Yes, in the early days of SASS, there were rules about writing format. If you don’t write like this, it will give you an error. This is very difficult to accept, especially for those of us who have been writing CSS for several years
The second point that can not accept SASS is the installation is more troublesome, engaged in front-end development personnel, the computer is basically no less node can be directly installed with NPM package manager, which is very convenient, while sass is relatively troublesome, but also need to install Ruby first. Because Sass is developed in Ruby (which comes with the MAC, as I later learned), it’s an extra step in the process. In addition, less can be directly run in the client as a JS file, which undoubtedly shortens the distance between front-end developers, so in the early days, everyone is inclined to less.
Bootstrap 3.0 was developed with less. For previous years, less was enough to satisfy everyone’s needs.
But after several years of development, everyone’s technology is improving, the demand is becoming more complex, at this time less is a little powerless, not that it is not good, but for several years of senior programmers, we need a more powerful CSS preprocessor.
At this time, I looked back and found that SASS had been with us all the time. I looked at its document. Although it was a little messy, it met our needs in all aspects and became more and more pleasing to my eyes. And now SASS has been upgraded to be fully compatible with CSS3, adding variables, nesting, mixing and other functions on the basis of CSS. The function can be used to calculate the color value and attribute value, provide advanced functions such as control instructions, and even customize the output format
On the other hand, with the implementation of various frameworks, less and SASS compilation work is becoming easier and easier, just install a loader, do not need to install the compiler globally. Many of the editors also compile themselves, eliminating all of the early advantages of less. So, next, come and see Sass with me
As you already know, SASS is a CSS preprocessor language. What is a CSS preprocessor language?
Simply put, CSS preprocessor defines a new language, the basic idea is to use a special programming language, add some programming features for CSS, CSS as a target file, and then developers just use this language to code. There are some basic features in a programming language that can make your CSS simpler, more adaptable, more readable, and easier to maintain.
A little more popular, like classical Chinese and vernacular Chinese. Classical Chinese a few words, translated into vernacular Chinese is a piece of article. Of course it’s just an analogy here.
The basic concepts are clear. Sass has so many useful features, but how can I use Sass in my projects? Please look down
Ii. Installation and use
As mentioned earlier, Sass is developed in Ruby, so you need to install Ruby before you can install Sass
A few points to note here:
- The Mac system comes with Ruby, so you don’t need to install it again, so the following installation method is only applicable to Windows.
- Some plugin-based editors, such as vsCode and Atom, do not need to install sass and can be compiled by installing plug-ins.
To install Sass on Windows, you need to install Ruby first. Download Ruby from the official website and install it. Check Add Ruby Executables to your PATH to Add system environment variables during installation. The diagram below:
After the installation is complete, to test whether the installation is successful, run the following command from the command line tool (CMD) :
Rubu -v if successful installation will print the following words: ruby 2.2.2 ruby installed, we can use the ruby gem installed Sass package management tool, is also in the Cmd, run the following command:
gem install sass
Copy the code
After the installation is complete, check whether the following installation is successful the old-fashioned way:
Sass -v, if installed successfully, prints the following code: Ruby sass 3.7.4Copy the code
With that, we’re basically ready to play. Here are some other related commands:
Update SASS: gem update sass View SASS version: sass -v View SASS help: sass -hCopy the code
Now let’s write some sASS code:
body{
margin: 0;
background: #fefefe;
}
.box{
width: 100px;
height: 100px;
border: 1px solid # 899;
}
Copy the code
You are not wrong, the above looks and CSS almost exactly the same code is actually SASS code! Isn’t that amazing? Of course, this code will compile and use the same effect as CSS. If you don’t have any experience with CSS preprocessing languages, you can write your code just like CSS. If you’ve learned one trick or two while reading this, it’s a promotion.
Sass has two file suffixes, one is.sass and the other is.scSS. SCSS is an updated version of sass, they are all called sass but the file suffixes are different. And then the.sass file is in fixed code format, as I mentioned in the beginning: get rid of “{}”, get rid of “;” This makes the code look a little weird, but get used to it. And.scss suffix ending file is more friendly, how to write, and it is an upgraded version, so we use.scss in the process of use, ok
After writing the SASS code, we need to compile sASS into CSS and apply it to our project. This process is called compilation.
3. Compile (translate Sass to CSS)
There are many ways of sASS compilation, such as command line compilation mode, editor automatic compilation, compilation software Koala, Sass – Loader, etc.
Let’s start with the first one: command-line compilation
I have created a style. SCSS file in the test folder. Now I need to compile this file into a CSS file, so I can use the command line tool to go to this folder.
CD test into the folder and then use sass compile command: Sass input.scss output.css is compiled successfully without any warning, but the output.css file will appear immediately in the folder. The input is the name of the original SCSS file, and output is the name of the compiled CSS file. You can do whatever you want, just stick to the basic naming rulesCopy the code
Commands can also be used to monitor a file in real time and automatically complete the compilation process when the file changes
Sass is watching for changes. Press ctrl-c to stop. // Sass --watch input. SCSS :output. CSS As prompted, press Ctrl + C at this time to stop this command. If the file is changed during listening and automatic compilation succeeds, the following code will be printed: >>> Change detected to: tests.scss write output.css write output.css.mapCopy the code
Commands can also be used to monitor a folder in real time, and all SCSS files in that folder are listened to
Sass -- watch targetFolder: outputFolder after listening success will print the following code: > > > sass is watching for changes. Press ctrl-c to stop.Copy the code
The preceding targetFolder is the targetFolder to listen to, and the following outputFolder is the folder to output. For example, if I want to compile SCSS files from the CSS folder into the style folder, I can say:
sass --watch css:style
Copy the code
Note that you need to be in the same parent of the CSS and Style folders to enable this function, otherwise an error will be reported
You can also adjust the output file at compile time in conjunction with compile options
Sass provides four compilation formats:
- nested
- expanded
- compact
- compressed
Look at the differences:
// Uncompiled styles.box {
width: 300px;
height: 400px;
&-title {
height: 30px;
line-height: 30px; }}Copy the code
. Nested compilation typesetting format:
/* Command line content */
sass style.scss:style.css --style nested /* compiled style */.box {width:300px;
height: 400px; }
.box-title {
height: 30px;
line-height: 30px; }
Copy the code
. Expanded Layout format:
/* Command line content */
sass style.scss:style.css --style expanded /*300px;
height: 400px;
}
.box-title {
height: 30px;
line-height: 30px;
}
Copy the code
. Compact compiles typesetting format
/* Command line content */
sass style.scss:style.css --style compact /* compiled style */.300px; height: 400px; }
.box-title { height: 30px; line-height: 30px; }
Copy the code
. Compressed compiles typesetting format
/* Command line content */
sass style.scss:style.css --style compressed /* style compressed */.300px;height:400px}.box-title{height:30px;line-height:30px}
Copy the code
The resulting code in different compilation formats is actually the same, but the layout format is different, so you can use it as you see fit. My recommendation is to use expanded format when developing. When you publish your code, use compressed, which makes CSS files relatively small.
Second: editor directly compiled (take webStorm as an example)
Compared with the first compilation method, using the editor to help us compile saves us a lot of operations in the development process, such as CD command to enter a folder, exit the folder and so on, and not everyone is familiar with the command operation mode. At this point, it seems that this compilation method may be more useful, I work in most of the process is also used to compile this way, let’s see the specific operation:
Note that the basis of compiling with the editor is also installing Sass, so the Sass installation process is essential!!
Now that we want the editor to help us do things, we need to adjust some of the editor’s configuration.Open Setting > Tools > File Watchers in turn, and the interface is roughly as follows:
After opening it, click the plus sign in the lower left corner and select SCSS in the popup interface
After selection, a window will pop up:There are two items that need to be adjusted in this window. I have marked them in red. The first item is Program
- On a Windows PC, Ruby is in the folder where you installed It, usually on drive C if not modified:
C:/user/username/AppData/Roaming
- On a Mac, press Command + Shift + G in the usr/local/bin window and enter usr/local/bin
Find a file named SCSS in the folder:
The second item, Arguments, is mainly used to set the compile parameters. For example, the four compile formats mentioned above can be loaded
Other editors, such as VsCode, are easier. It doesn’t need to install sass, just install the plugin. Search for sass in the plugin library, and just pick one.
Third: compilation software Koala
Attached is the official website: http://koala-app.com/
This is a small software, download and install on the official website can be, the official website can automatically distinguish Windows system or Mac system, so directly click download can be.Just drag the files you want to compile or the entire folder into the software as prompted
Click on a file, and a menu pops up on the right. Check Auto Complie at the top to automatically listen, and then there are some options, such as the four compile formats we mentioned earlier: sass provides four compile formats: Nested, expanded, compact, compressed can be selected here, and finally click compile at the bottom to complete
Fourth, use sass in the framework
Today’s front-end environment, framework has become the mainstream of development, so this aspect needs everyone to work hard to study, here I say in Vue how to go is to use SASS
First we set up a simple project using the Vue Cli
Install Vue Cli first, if you do not know about Vue Cli, you can go to the official website to see the introduction
Vue Cli can be installed directly through the NPM package manager, so we can type the command directly:
npm install -g @vue/cli
Copy the code
After installing the Vue Cli, you can create a project directly using the Vue command:
vue create projectname
Copy the code
A few points to note here:
Make sure to go to the folder where you want to create the project and run the CD command
- Projectname you can customize it according to the naming convention, but you can’t use uppercase letters
- After creating your project, Vue will create a new folder named projectName in your folder, which will be the project’s home directory
- After creating the project, you need to enter the project folder to run the project
Once you’ve created your project, open it with an editor and it looks something like this:
The Vue Cli has already integrated everything necessary for us, but we still need to install two dependencies, Sass-loader depends on Node-sass, so you need to install a Node-sass. You can directly open the command line tool in the editor to install it, so that you can save the time to use the CD command to enter our project folder
After opening:
Pay attention to the current folder!! Then type the command directly:
npm install sass-loader node-sass --save-dev
Copy the code
The original SASS file needs to be processed by CSS-loader style-loader, but the Vue Cli has helped us deal with it, even the webpack configuration has been processedSo we don’t need to worry about the process behind, of course, interested students can also go to the Webpack will have a detailed explanation.
After installation, you can see it in package.json file. The version may be differentEverything is ready, then you can be happy with the code!
Style =” SCSS “style =” SCSS” style =” SCSS”
Then type the command directly:
npm run serve
Copy the code
Just run the project!
Common Node-Sass installation failure handling method: Switch NPM resources to domestic Taobao mirror:
- Taobao NPM address: npm.taobao.org/
- NPM install -g CNPM — registry.npm.taobao.org
- Temporary use: NPM –registry registry.npm.taobao.org install Express
4. The grammar
Through the previous points, the manual of Sass has been issued to you, students who have not had time to read it can be turned over, the main idea here is the functional manual of Sass, you see the official ready melon seeds fruit…
1, the variable
Variables are derived from mathematics, which is an abstract concept in computer language that can store calculation results or represent values. Variables are useful because they allow you to assign a short, easy-to-remember name to each piece of data you plan to use in your program.
I don’t think 250px is a good value, so I’ll call it SB, so I can write it like this:
$SB:250px;
.box{
width: $SB;
height: 20px;
}
Copy the code
Now, the width of the box is 250px, even though I wrote it as SB. As for the dollar “$” sign, it’s actually a sign that tells Sass that it’s a nickname, not a real SB.
This nickname comes in handy, and if you want to change the width of the box in the future, you can just say: SB change! Make it 100px, and then the box will be 100px wide.
Here’s an example:
Now I have a rectangle, a triangle, and a button on the page. These are all common elements in our pages. They all use a color that I can’t tell you. It’s not very nice anyway.
$color: # 899;
.box{
width: 200px;
height: 200px;
border: 5px solid $color; / * -- -- -- -- -- -- -- -- -- -- -- -- - * /
float: left;
}
.arrow{
margin: 100px;
width: 0;
height: 0;
border-width: 40px 20px 0;
border-style: solid;
border-color: $color transparent transparent transparent; / * -- -- -- -- -- -- -- -- -- -- -- -- - * /
float: left;
}
.btn{
width: 100px;
height: 40px;
margin-top: 96px;
border: 1px solid $color; / * -- -- -- -- -- -- -- -- -- -- -- -- - * /
border-radius: 4px;
color: $color;
text-align: center;
line-height: 40px;
float: left;
}
Copy the code
At the beginning of the code I define a variable:$color: #899
; It is then applied separately to tags in the code. At this point we can say that the colors of the three elements in the diagram above are all dependent on variables$color
We have variables. When we need to change the color, just go ahead and change the value of the variable. For example, now we want to change them to pink:All I have to do is change the variable
$color: #f991ff;
Copy the code
Results obtained:
$color = $color = $color = $color = $color = $color = $color = $color = $color = $color = $color = $color
Now we know that variables declared in a.css can only be used in A.css. This is provided that the variable declaration is not wrapped in anything. Such as:
.box{
$zhuangBiFan: #00afff;
width: 200px;
height: 200px;
border: 5px solid $color;
float: left;
}
Copy the code
In this code, variables$zhuangBiFan
You can say the selected.box
Wrapped up, so this variable is in.box
You can’t use it outside of that and you can say variables$zhuangBiFan
The scope of action is in the selector.box
The inside. Scope, there is a more professional name, called scope, in fact, domain is the meaning of scope, but called scope will appear a little bit taller, so call him scope ~
However, Sass also provides a variable escape method, which is to add a global after the variable:
#main{$width: 5em! global;width: $width;
}
#sidebar {
width: $width;
}
Copy the code
In this case, variables in #main can also be used in #sidebar.
Another interesting point: the value of a variable can refer to other variables!!
$color: #f991ff;
$globalBorder: 1px solid $color;
.box{
border: $globalBorder; } after compiling:.box {
border: 1px solid #f991ff;
}
Copy the code
Css3 actually also has variables, but the definition and use of sASS is not so convenient. In my other article: I used the native CSS variables. It had this passage in it:
.eyes:before,
.eyes:after{
content: ' ';
position: absolute;
top: 110px;
width: 100px;
height: 100px;
background-color: #4e4e4e;
border-radius: 50%;
background-image:
radial-gradient(circle at var(--left1), white 1px, transparent 1px),
radial-gradient(circle at var(--left2), black 10px, transparent 11px),
radial-gradient(circle at var(--left3), white 30px, transparent 31px);
}
.eyes:before{
left: 26%;
--left1: 84px;
--left2: 80px;
--left3: 64px;
}
.eyes:after{
right: 15%;
--left1: 16px;
--left2: 19px;
--left3: 36px;
}
Copy the code
The variables are left1, left2, and left3. These variables have different values for before and after due to scope reasons, so the final result is different.
--name:value; When used: var(--name)Copy the code
The CSS variable declaration must be included, not directly — name:value; Consider writing this:
:root{
--name:20px; / * * / declaration
}
.box{
width: var(--name); / * * / use
}
Copy the code
2, the nesting
Sass allows one set of CSS styles to be nested within another set of styles, with the inner style having its outer selector as its parent. Consider using CSS to implement the following layout: [](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/9bcb85fa78544f8fa30f00c1dd9b09e9~tplv-k3u1fbpfcp-watermark.image)
So with CSS we might write:
nav {
height: 40px;
border-bottom: 1px solid # 333;
line-height: 40px;
}
nav ul {
float: left;
height: 100%;
}
nav ul li {
float: left;
height: 100%;
border-right: 1px solid # 333;
padding: 0 20px;
}
Copy the code
As you can see, both selectors have the same parent nav. Now let’s rewrite this code using sass nesting:
nav{
height: 40px;
border-bottom: 1px solid # 666;
line-height: 40px;
ul{
float: left;
height: 100%;
li{
float: left;
height: 100%;
border-right: 1px solid # 333;
padding: 0 20px; }}}Copy the code
The result after compilation:
nav {
height: 40px;
border-bottom: 1px solid # 666;
line-height: 40px;
}
nav ul {
float: left;
height: 100%;
}
nav ul li {
float: left;
height: 100%;
border-right: 1px solid # 333;
padding: 0 20px;
}
Copy the code
You can see that the compiled code is exactly the same as the previous CSS code, but the sASS code is much more hierarchical, so you don’t have to look at the irrelevant code, you can see that the nav contains UL and then ul contains Li. All included selectors are treated as children of the outer selector. At compile time, sass takes out the name of the parent selector, then adds the child selector itself, with a space in between, and prints it to CSS to form the normal CSS code we see compiled. But that can create a problem.
When the mouse is over Li, we want the background color of Li to be gray and the text color to be white, so we might write the following code:
nav{
height: 40px;
border-bottom: 1px solid # 666;
line-height: 40px;
ul{
float: left;
height: 100%;
li{
float: left;
height: 100%;
border-right: 1px solid # 333;
padding: 0 20px;
:hover{
background: # 999;
color: #fff; }}}}Copy the code
At first glance it looks fine, but let’s look at the compiled code:
nav {
height: 40px;
border-bottom: 1px solid # 666;
line-height: 40px;
}
nav ul {
float: left;
height: 100%;
}
nav ul li {
float: left;
height: 100%;
border-right: 1px solid # 333;
padding: 0 20px;
}
nav ul li :hover {
background: # 999;
color: #fff;
}
Copy the code
A close look at li’s pseudoclass style shows that the original li: Hover has an extra space in the middle. This is also in accordance with sASS’s compilation rules, which combine the names of all the parent selectors with the child selectors into a descendant selector, which requires a space in the middle. But now we need to remove this space, and we need to manually tell sass what to do, which is the ampersand:
nav{
height: 40px;
border-bottom: 1px solid # 666;
line-height: 40px;
ul{
float: left;
height: 100%;
li{
float: left;
height: 100%;
border-right: 1px solid # 333;
padding: 0 20px;
&:hover{
background: # 999;
color: #fff; }}}}Copy the code
You can see that I have added the “&” symbol to the beginning of :hover, so it will compile normally:
nav {
height: 40px;
border-bottom: 1px solid # 666;
line-height: 40px;
}
nav ul {
float: left;
height: 100%;
}
nav ul li {
float: left;
height: 100%;
border-right: 1px solid # 333;
padding: 0 20px;
}
nav ul li:hover {
background: # 999;
color: #fff;
}
Copy the code
The ampersand replaces the parent and child selectors of the nearest hierarchy to form the descendant selectors.
- Get the names of all parent selectors: nav ul Li and then &:hover to form offspring selectors
- Then replace the ampersand with the nearest parent selector to form the nav ul Li :hover to form the offspring selector
So it’s not uncommon to see someone write something like this:
.form {
padding-top: 0.44 rem;
&__item {
position: relative;
height: 1.173333 rem; & -clear {
position: absolute;
bottom: 0.253333 rem;
}
&-imgcode {
position: absolute;
top: 0.253333 rem;
img {
width: 100%;
height: 100%;
}
}
}
&__submit {
display: block;
text-align: center;
font-family: 'PingFangSC-Medium';
&--disabled {
background-color: # 899; }}input {
height: 0.493333 rem;
font-size: 0.346667 rem; }} after compiling:.form {
padding-top: 0.44 rem;
}
.form__item {
position: relative;
height: 1.173333 rem;
}
.form__item-clear {
position: absolute;
bottom: 0.253333 rem;
}
.form__item-imgcode {
position: absolute;
top: 0.253333 rem;
}
.form__item-imgcode img {
width: 100%;
height: 100%;
}
.form__submit {
display: block;
text-align: center;
font-family: 'PingFangSC-Medium';
}
.form__submit- disabled {background-color: # 899;
}
.form input {
height: 0.493333 rem;
font-size: 0.346667 rem;
}
Copy the code
You can see one benefit of writing SASS code this way:
- All selector levels after compilation have only one level
- All selector names are accompanied by the name of the parent selector, effectively avoiding naming conflicts
- Sass code is still very clear to see the code hierarchy
Some CSS properties follow the same namespace. For example, font-family, font-size, and font-weight all use font as the namespace for the property. To facilitate the management of such attributes, and to avoid duplicate input, Sass allows attributes to be nested in namespaces, such as:
.funky {
font: {
family: fantasy;
size: 30em; weight: bold; }} after compiling:.funky {
font-family: fantasy;
font-size: 30em;
font-weight: bold; }
Copy the code
Even namespaces can contain their own attribute values, for example:
.funky {
font: 20px/24pxfantasy{ weight: bold; }} after compiling:.funky {
font: 20px/24px fantasy;
font-weight: bold; }
Copy the code
CSS has many similar properties, such as border, background, margin, padding, etc.
3, mixed
We already know about variables in SASS, but variables can only record a value. At most, all values of an attribute can be recorded, such as:
This makes it easy for the box selector to get a border style, but what if I have a lot of common styles? For example, text color and font size can be unified. At this time, it is not convenient for us to save variables one by one and then use them. Mixins are designed to solve this problem by packaging a whole piece of code and then using it as a variable elsewhere.
$primary-border:1px solid #899;
.box{
border:$primary-border;
}
Mixins are used to define reusable styles, avoiding the use of nonverbal classes. Hybrid instructions can contain all CSS rules, most Sass rules, and even introduce variables through parameter functions to output a variety of styles.
Case study:
Considering the implementation of the button in the diagram, let’s write it in the same way as before:
$btnHeight: 40px;
$grayBorder: 1px solid #bbb;
$blueBorder: 1px solid #4395ff;
.btnGray{
height: $btnHeight;
border: $grayBorder;
padding: 20px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
}
.btnBlue{
height: $btnHeight;
border: $blueBorder;
padding: 10px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
}
Copy the code
It can be seen that although we use variables a lot in the above code, the similarity between the contents of the two selectors is still very high. You may think that clearly border-radius, font, text-align can be defined by variables, but think carefully, is such code really what we need? If it’s a little bit more complicated it’s all variables, right? This will write more and more disorderly I’m afraid! So with code like this, we need to mix
hybrid
Now let’s see what we can do with mixing:
@mixin btn{
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
}
.btnGray{
@include btn;
border:1px solid #bbb;
padding: 20px;
}
.btnBlue{
@include btn;
border:1px solid #4395ff;
padding: 10px; } after compiling:.btnGray {
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border: 1px solid #bbb;
padding: 20px;
}
.btnBlue {
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border: 1px solid #4395ff;
padding: 10px;
}
Copy the code
You can see that the code becomes very clear. Let’s look at what happens in this code: in the first paragraph, we use the @mixin directive to create a “super variable” : BTN, and this “super variable” is a collection in which all CSS rules can be written. This “super variable” is then referenced via the @include directive. In this way, we can extract the duplicate code from several similar selectors and achieve high reusability of the code. Sass calls this definition of a “super variable” and reference to a “super variable” mixed.
Of course, we might consider writing a common class and then importing it where necessary, but such code is not maintainable, and performance is certainly not as good as sASS, and the sASS hybrid is more powerful, see below.
Parameters in the mix
In the above code, although I have extracted all the duplicate code, the remaining two attributes: border and padding are not very different from each other. Is it possible to extract these two attributes as well? Yes:
@mixin btn($color) {height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border:1px solid $color;
}
.btnGray{
@include btn(#899);
padding: 20px;
}
.btnBlue{
@include btn(#4395ff);
padding: 10px; } after compiling:.btnGray {
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border: 1px solid # 899;
padding: 20px;
}
.btnBlue {
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border: 1px solid #4395ff;
padding: 10px;
}
Copy the code
As you can see in this code, the compiled code is the same as the previous code, but the sass code is a little more concise ———— when defining the mixed style BTN, we put a parentheses behind it. The parentheses are actually a variable name, but the variable has no value. Then you can see that this variable is used in the following: border: 1px solid $color; This variable is used here.
$color = $color; $color = $color; $color = $color; $color = $color; Then replace yourself as a whole where the hybrid style is introduced. This process may seem a little complicated, but say this:
We thought of the whole process as going to the deposit.Different customers came with different keys, so the items must be different, but suddenly the deposit.All customers came to pick up their items, and they sent a box of eggs! Different customers (.btnGray,.btnBlue) come to BTN with different keys (#899, # 4395FF), and BTN will take out different items according to different keys (.bTNgray gets: Border: 1px solid #899, while. BtnBlue gets: border: 1px solid #4395ff). Finally,.btnGray and.btnBlue both got the common style and got a different color border style
@mixin btn($color) {height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border:1px solid $color;
}
.btnGray{
@include btn(#899);
padding: 20px;
}
.btnBlue{
@include btn(#4395ff);
padding: 10px;
}
Copy the code
Looking at this code again, it parses from top to bottom, lines 1 through 7 are not parsed at first because it has not been called as a mixed style in the meantime. So it doesn’t parse
At line 10 you see an @include directive followed by the name BTN. Sass will then look for a blended style named BTN, which looks a bit familiar, and immediately grabs the BTN on line 17: “Here you are!” BTN line 10 has a key in parentheses, so line 17 is replaced with this:
@mixin btn{
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border:1px solid # 899;
}
Copy the code
Then copy this code to line 10, and the selector.btngray gets the complete code. Lines 1 through 7 are immediately restored as soon as the substitution is complete. The code continues down to line 15 and, alas, this place still needs the guy, so BTN is picked up again… Repeat.
Note: a mixed style of parameters is defined. Parameters must be passed or an error will be reported
At this point, mixing things seems a little bit clearer. But if you’re careful, you might notice that the padding in the two selectors works the same way.
@mixin btn($color,$pad){
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border:1px solid $color;
padding: $pad;
}
.btnGray{
@include btn(#899.20px);
}
.btnBlue{
@include btn(#4395ff,10px);
}
Copy the code
Yes, the variables behind the blending styles are actually called parameters, which are used to set the variables and assign values to the styles in the blending instruction. When defining mixed instructions, write parameters in parentheses, separated by commas, in the format of variables. When referencing instructions, write the assigned values in parentheses according to the order of arguments
Note that multiple parameters can only be passed in the order defined. If you want to change the order of parameters, you can write:
.btnGray{
@include btn($pad: 20px, $color: #899);
}
Copy the code
Parameter Default Value
Even hybrid directives can assign default values to arguments using the method of assigning values to variables, and then automatically use the default values if the argument is not assigned when the instruction is referenced:
@mixin btn($color: #899, $pad: 20px) {height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border:1px solid $color;
padding: $pad;
}
Copy the code
The variables color and color and color and pad have default values, and when called, if no value is passed in, these two variables will get the default values defined here
.btnGray{
@includebtn; } after compiling:.btnGray {
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border: 1px solid # 899;
padding: 20px;
}
Copy the code
Note: If you define multiple variables, you can specify the variable name when you want to change only one of them. For example, now that our blending style has a default value, I need to change the padding of.btngray to 10px.
If we write this:
.btnGray{
@include btn(10px); } after compiling:.btnGray {
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border: 1px solid 10px; /* The first argument passed in is placed in this position */ by default
padding: 20px;
}
Copy the code
This is definitely wrong, so we can specify the variable name:
.btnGray{
@include btn($pad: 10px); } after compiling:.btnGray {
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border: 1px solid # 899; /* The default value */ will be used
padding: 10px; /* Specifies the variable to replace the value here */
}
Copy the code
Some tips
1. In blending styles, you can introduce other blending styles:
@mixin compound {
@include highlighted-background;
@include header-text;
}
@mixin highlighted-background { background-color: #fc0; }
@mixin header-text { font-size: 20px; }
.box{
@includecompound; } after compiling:.box{
background-color: #fc0;
font-size: 20px;
}
Copy the code
2. You can treat the entire selector as part of a blending style, which is useful when modularizing code:
@mixin silly-links {
a {
color: blue;
background-color: red; }}.box{
@includesilly-links; } compile to:.box a {
color: blue;
background-color: red;
}
Copy the code
3. If you are not sure about the number of parameters, you can write:
@mixin box-shadow($shadows...) {
-moz-box-shadow: $shadows;
-webkit-box-shadow: $shadows;
box-shadow: $shadows;
}
.shadows {
@include box-shadow(0px 4px 5px #Awesome!.2px 6px 10px #999);
}
Copy the code
4, inheritance
@ the extend 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. So at @extend we could say:
General style:.normal{
color: #00d5e8;
background: #e8e000; } Special style:.special{
@extend .normal; /* Inherit all the styles in the normal selector */
padding: 10px; } after compiling:.normal..special {
color: #00d5e8;
background: #e8e000;
}
.special {
padding: 10px;
}
Copy the code
As you can see, when Special inherits from Normal, they both have the color and background attributes, so Sass puts the two attributes together to form a group selector, and then takes the styles unique to Special to form a selector.
Here’s another example:
Consider the implementation:
.btn{
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
}
.btnGray{
border:1px solid #bbb;
padding: 20px;
}
.btnBlue{
border:1px solid #4395ff;
padding: 10px;
}
html: <div class="btn btnGray"></div>
<div class="btn btnBlue"></div>
Copy the code
This is what we used to do in the CSS era. Now with inheritance, we can consider saving some code:
.btnGray{
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border:1px solid #bbb;
padding: 20px;
}
.btnBlue{
@extend .btnGray;
border:1px solid #4395ff;
padding: 10px; } after compiling:.btnGray..btnBlue {
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border: 1px solid #bbb;
padding: 20px;
}
.btnBlue {
border: 1px solid #4395ff;
padding: 10px;
}
Copy the code
You might be thinking why don’t I just have btnGray and btnBlue inherit from BTN? Notice the code at the top. Normal, as an inherited style, also appears in CSS files after compilation. In this case, we don’t need a separate BTN class, so I just let btnBlue inherit all the styles of btnGray, and then add btnBlue’s unique styles. Using the cascading effect of CSS code, the repeated code is automatically overwritten. The effect is completely unaffected.
In the process of inheritance, we can even inherit the related style of the inherited style. For example, we can add a hover pseudo-class to btnGray. Remember how to write the pseudo-class in nesting?
.btnGray{
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border:1px solid #bbb;
padding: 20px;
&:hover{
background-color: #fefefe; }}.btnBlue{
@extend .btnGray;
border:1px solid #4395ff;
padding: 10px; } after compiling:.btnGray..btnBlue {
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border: 1px solid #bbb;
padding: 20px;
}
.btnGray:hover..btnBlue:hover {
background-color: #fefefe;
}
.btnBlue {
border: 1px solid #4395ff;
padding: 10px;
}
Copy the code
You can see that both btnGray and btnBlue have the hover pseudo-class. How about adding some other styles?
.btnGray{
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border:1px solid #bbb;
padding: 20px;
&:hover{
background-color: #fefefe;
}
.item{
width: 200px;
height: 200px; }}.btnBlue{
@extend .btnGray;
border:1px solid #4395ff;
padding: 10px; } after compiling:.btnGray..btnBlue {
height: 40px;
border-radius: 4px;
font: 24px/40px Microsoft Yahei;
text-align: center;
border: 1px solid #bbb;
padding: 20px;
}
.btnGray:hover..btnBlue:hover {
background-color: #fefefe;
}
.btnGray .item..btnBlue .item {
width: 200px;
height: 200px;
}
.btnBlue {
border: 1px solid #4395ff;
padding: 10px;
}
Copy the code
Now, as you can see, this thing is very similar to @mixin. So are we going to inherit or mix?
Here we first summarize the difference between blending and inheritance:
- Inheritance also outputs inherited styles to CSS files, while hybrid styles are not compiled into CSS files
- Inheritance tries to pull code together to form group selectors, while blending does not
- Blending defines parameters, inheritance does not
In most cases, @mixin is actually better than @extend, but both have their place. Use @extend when the relationship between styles and selectors is tight in some way. In addition, you can use @mixin anywhere.
5. Control instructions
Sass provides some basic control instructions, such as referencing styles when certain conditions are met, or setting a range to repeat the output format. Control instruction is an advanced function, which is not often used in daily writing. It is mainly used with mixins
@if
@if is used to define conditions that do something when the input value meets the conditions. When the @if expression is true, output the code in {} :
p{
@if 1 + 1= =2 { width: 20px}}Copy the code
If (1+1 == 2) {} if (1+1 == 2) {} if (1+1 == 2) {} if (1+1 = 2) {} if (1+1 = 2) {}
p{
width: 20px;
}
Copy the code
Here are the operations in Sass:
Sass supports the addition, subtraction, multiplication, division and rounding operations of all numbers. The operators are as follows:
- Add +
- Subtracting the –
- Multiply *
- Division /
- Integer %
And limited unit conversions occur when the units between two values are not uniform, as in:
p{
width: 2 * 20px; } compile to:p{
width: 40px;
}
Copy the code
Sass can’t handle two values with different units, so don’t write code like this:
p{
width: 2em * 20px;
}
Copy the code
In addition, the relational operations <, >, <=, >= can also be used for number operations, equality operations ==,! = is available for all data types. Because the/sign is sometimes used as a semicolon rather than a division, be careful when using it:
1. Do not deduct
.main{
width: 120px/2; } after compiling:.main{
width: 120px/2; } Parentheses solve the problem:.main{
width: (120px/2);
}
Copy the code
2. Unit elimination
.main{
width: (120px/2px); } after compiling:.main{
width: 60; } Solution: Try not to have units on both sides of an operationCopy the code
3. Font composite style: Given that the mobile layout needs to replace units, we might write:
$rem: 30rem;
p{
font: 120px/$rem / 30px/$rem Arial; } First of all, if there are units on both sides of the division sign and they are not uniform, an error will be reported directly. $rem: $rem: $rem: $rem: $rem:30;
p{
font: # {(120rem/$rem)} / (30rem/$rem) Arial; } after compiling:p {
font: 4rem / 1rem Arial;
}
Copy the code
#{} We can use variables in selectors or property names by using interpolation statements:
$name: foo;
$attr: border;
.#{$name} {
#{$attr}-color: blue; } after compiling:.foo {
border-color: blue;
}
Copy the code
We can use variables in the selector name, which is a very useful feature to use in the future, but now we continue with the control instructions:
@ for loop
The @for directive can repeat the output format within limits, changing the output each time as required (the value of the variable). This directive has two formats: @for $var from through, or @for $var from to, depending on the meaning of through and to: When using through, the conditional range contains the values of and, whereas when using to, the conditional range contains only values that are not included in the values. In addition, $var can be any variable, such as $I; The sum must be integer values.
Such as:
@for $num from 1 through 3 {
.item{
width:$num * 3px; }} after compiling:.item {
width: 3px;
}
.item {
width: 6px;
}
.item {
width: 9px;
}
Copy the code
As you can see from the code above,.item is looping out three times. The values of the num variable are different each time, as you can see from1, 2, and 3, which is exactly the way from1through3 is set, from1through3. The @for control is a little bit more complicated, and we can change the values of num to 1, 2, and 3, which is the same as from 1 through 3, from 1 to 3. The @for command is a little bit more complicated, and we can change the values of num to 1, 2, and 3, which is exactly what from1through3 does, from1through3. The @for control is a little more complicated. We can also use the num variable in the selector name, so that the output selector is not the same. Remember the interpolation statement mentioned above? That’s it: #{}
Ok now we generate 3 selectors at once with @for, of course we can generate more, for example consider the following case:
.box{
width: 200px;
height: 200px;
border: 1px solid # 899;
border-radius: 50%;
position: relative;
.item{
width: 2px;
height: 10px;
background: # 899;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
@for $num from 1 through 12 {
.item:nth-child(#{$num}){
transform: rotate((360deg/12)*$num) translateY(-96px); }}} the compiled code you can probably guess, so it is not included hereCopy the code
@each
The format of the @each directive is $var in. $var can be any variable name, such as $length or $name, but is a list of values.
@each applies the variable $var to each item in the list of values and prints the result, for example:
@each $animal in puma, sea-slug, egret, salamander {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png'); }} after compiling:.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
@while
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. Such as:
$i: 6;
@while $i > 0 {
.item-# {$i} { width: 2em * $i; }
$i: $i - 2; } after compiling: item-6 {
width: 12em; }
.item-4 {
width: 8em; }
.item-2 {
width: 4em; }
Copy the code
As you can see, the function of while is similar to that of @for, except that @while can loop according to certain rules instead of increasing or decreasing
6, other
CSS also has the @import attribute. If sass mentions it again, will it be unnecessary? Let’s examine the @import of CSS
- It’s more for media queries
- Each time it imports a file, it sends a request to the server
- It does not merge the incoming file with the current file
- Variables defined in the import file cannot be used in the current file
Sass extends @import to allow it to import SCSS or Sass files. The imported files are merged and compiled into the same CSS file, and variables or mixins contained in the imported file can be used in the imported file. Sass extended @import cannot contain the following information:
- The file extension is.css
- The file name starts with http://;
- The filename is url();
- Cannot contain media queries.
@import can import files with extension names.scss and.sass. If no extension name is specified, Sass will try to find a file with the same file name, extension.scss or.sass and import it to, for example
@import "style.scss"Or @ import"style"
Copy the code
Both lines can be imported into the style.scss file
In addition, Sass can import the Sass file as a component instead of compiling the component as a CSS file. To do this, you just need to put an underscore in front of the file name like _components. SCSS and the editor doesn’t automatically compile the file, Only when we import this file in another SCSS file will the contents of this file be compiled into the imported file:
I now have two SCSS files set up in the project
- _components.scss
- style.scss
You can see that _components. SCSS is not compiled by the editor, just a single SCSS file, while the style. SCSS file below is compiled as a CSS file with a map file attached.
We can also see that @mixin defined in _components is normally used in style, which means that we can extract some common files and import them where we need them. This is very helpful for modular development.
Open the source code of Bootstrap, you can see that there are many SCSS files defined in bootstrap. We can call these files as components, each component is responsible for only one function module, and then introduce them into a summary SCSS file. Even components can reference each other and depend on each other. So we only need to care about the final SCSS file in the end. Such components are called Partials by Sass.
Even, in Sass, @import can be used for nesting:
.example {
color: red;
}
#main {
@import "example"; } after compiling:#main .example {
color: red;
}
Copy the code
2,@media
Another useful thing about Sass’s nesting system is @media. The basic usage of this directive is the same as in CSS, with the added feature of allowing it to be nested within CSS rules. If @Media is nested within CSS rules, @ Media will be compiled to the outermost layer of the file at compile time, including 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; }}Copy the code
For example, in this code, reading down from the top, it means: the sidebar is 300 wide and 500 wide when the mediating criteria are met and it will actually compile as I understand it
.sidebar {
width: 300px; }
@media screen and (orientation: landscape) {
.sidebar {
width: 500px; }}Copy the code
Even @media queries can be nested with each other. Sass automatically adds and when compiling
@media screen {
.sidebar {
@media (orientation: landscape) {
width: 500px; }}} after compiling:@media screen and (orientation: landscape) {
.sidebar {
width: 500px; }}Copy the code
The last
The above is my summary of the practical content of SASS, any questions welcome to ridicule