CSS Preprocessor language SASS Syntax: Learning SASS Grammar

Source: Internet
Author: User
Tags filter end extend functions header variables version variable




Article Introduction: In fact, the current SASS has two sets of grammatical rules: one is still using indentation as a delimiter to distinguish between blocks of code, and another set of rules and CSS like the use of braces ({}) as delimiters. The latter syntax rule, also known as SCSS, supports this grammatical rule in the SASS3 version. If there is no special explanation here, all refer to Scss.





What is SASS?






Sass is a ruby based on the CSS preprocessor, was born in 2007, is the earliest and most mature of a CSS preprocessor language, it can use variables, nesting, mixing, inheritance, operations, functions and other functions, so that the development of CSS, become simple and clear to maintain, At the same time, it also greatly saves the designer's time and improves the efficiency. Sass will eventually compile a legitimate CSS for the browser to use, that is, its own syntax is not too easy for the browser to identify, because it is not a standard CSS format, in its syntax can use dynamic variables, etc., so it is more like a very simple dynamic language.






In fact, the current SASS has two sets of grammatical rules: one is still using indentation as a delimiter to distinguish between blocks of code, and another set of rules and CSS like the use of braces ({}) as delimiters. The latter syntax rule, also known as SCSS, supports this grammatical rule in the SASS3 version. If there is no special explanation here, all refer to Scss.





why the sass?





Although Sass was the earliest, but at first still not very good, and use indentation as a separator, does not conform to CSS use curly braces habit, so less as an up-and-comer identity easily won the people, later sass learn from the less of some ideas, improve their design, and have a scss, Then after several versions of the update, the special version 3.2.0 made some revolutionary updates to make it stand out from several other compiler processors. Let's take a look at a few good ideas together.





    • default variable:Sass version 3.0 introduces the default variable!default to make the variable more controllable.
    • @content:sass Version 3.2.0 mixin is supplemented so that it can accept an entire block of styles, most of which are used in CSS3 @media situations.
    • placeholder Selector%:Sass Version 3.2.0 introduces the placeholder selector%, for mixin that do not pass parameters, you can consider using it later, because there are two advantages--no CSS is generated without calling, and the parsed CSS is stated in combination, Instead of the Mixin copy method.
    • variable arguments:the sass version 3.2.0 the variable parameter so that it can set parameters for CSS3 Multiple property values, such as box-shadow,transition they can have multiple values, separated by commas. and mixin parameters are separated by commas, so the CSS3 definition of some mixin will be an error, so there is a variable followed by three points to indicate that this parameter is to pass multiple values.





At present, Sass's library is also the most, in the convenience of our study, but also on the other hand to show its superiority.



SASS Syntax



Sass has two types of suffix file: a suffix named sass; the other is the Scss file we use here, which is similar to the CSS file format we usually write, using curly braces. All sass files mentioned in this tutorial refer to files with a suffix named Scss.



Import

The Sass Import (@import) rule differs from CSS in that it only imports different files semantically, but the end result is a CSS file. However, if you import a CSS file into a sass file,@import 'reset.css'it will not be merged into a single file, just like the normal CSS import style file. All SASS Import files can then ignore the suffix name.scss.

PS: Generally the basis of the file naming method to _ start, such as_mixin.scss. This type of file can be imported without underlining, as it can be written as@import "mixin"




Be imported sass file A.scss:


A.SCSS//-------------------------------body {   


Sass file B.scss to import styles:


@import "Reset.css"; @import "a"; p{   background: #0982c1;}  


Translated B.css style:


@import "Reset.css"; Body {   background: #eee;} p{   


According to the above code can be seen,b.scssafter compiling,reset.csscontinue to maintain the import of the way, but isa.scssintegrated in.



Comments

Sass has two ways of commenting, one is the standard CSS annotation/* */, the other is a//single-line annotation in the form of a double ramp, but the single-line annotation is not translated.




Standard CSS Annotations


* * I am the standard annotation of CSS * Set the body within the distance * * body{   padding  5px}  


//Double Diagonal Bar Single-line Annotation



Single-line comments are used with slashes (//), as are annotations in the JavaScript language, but Single-line comments are not entered in the CSS.


I'm a single line of comments with a double slash $mainColor: #369; Define Body Color   

Variable


You can also declare variables in sass and use them throughout the style sheet. SASS supports any variable (for example: color, numeric, text, and so on). Then you can refer to variables anywhere.



Sass declares that the variable must be the$beginning, followed by the variable name, and that the variable value and the variable name need to be(:)separated by a colon (just like the CSS property setting), if the value!defaultis followed by a default value. In general, we define variables as attribute values that can be used directly, and of course there is another use of variables to#{$variables}insert in form.


Sass Style//-------------------------------  
$baseLineHeight:        1.6;  
$baseFontSize:          
!default; $baseLineHeight:        
!default; $bodyBgColor:           
!default; $textColor:             #333!default;  $borderDirection:       
!default;   
Body {    font-size: $baseFontSize;   Line-height: $baseLineHeight;    Background-color: $bodyBgColor;   
. border-#{$borderDirection} {   border-#{$borderDirection}:1px solid #ccc;}  

body {    font-size:14px;   line-height:1.6;   Color: #333;   Background-color: #fff; }
. border-top{   


The above variables we use the default definition, but for line-height we have defined one in addition to the default value, so the actual parsing applies to our redefined, not the default. This design is very useful to introduce some basic sass files, we do not need to modify the introduction of the basic files, but directly before the introduction of the file, redefine the variables we need to change the OK.



In addition, a variable can contain multiple values and then passnth($variables,index)来调用其中的某个值


Sass Style//-------------------------------$linkColor:
         
a{   Color:nth ($linkColor, 1);
      &:hover{
     Color:nth ($linkColor, 2);   } }
  
a{   color: #08c;} a:hover{   



Nesting (Nesting)

Sass nesting includes two kinds: one is nesting of selectors, the other is nesting of attributes. What we usually say or use is the nesting of selectors.




Picker nesting



The so-called selector nesting refers to nesting another selector in one selector to implement inheritance, thus increasing the structure and readability of the sass file.



In selector nesting, you can use the&expression parent element Selector


Sass Style//-------------------------------
#top_nav {   
  Text-transform:capitalize;   Background-color: #333;
   li{     float:left;   }   a{     
    Padding:0 10px;
     Color: #fff;
      &:hover{       
    }}  //css style//-------------------------------
#top_nav {
   line-height:40px;   Text-transform:capitalize;   Background-color: #333; }   
#top_nav li{   
#top_nav a{   Display:block;   Padding:0 10px;   
#top_nav a:hover{   


Property nesting



Attribute nesting refers to some attributes that have the same starting word, such as theborder-width,border-colorbeginning of a border. Take an example of an official website to see:


Sass Style//-------------------------------
. Fakeshadow {
   border: {     style:solid;     Left: {       width:4px;       Color: #888;     }
     Right: {       width:2px;       Color: #ccc;     }   

. fakeshadow {   border-style:solid;   border-left-width:4px;   Border-left-color: #888;   border-right-width:2px;   Border-right-color: #ccc;  }


Of course this is just an example of an attribute nesting, and if it's actually used, it's going to go crazy.



Mixing (mixin)

Mixin is one of the most powerful features in sass, and he can extract some of the styles as separate modules and be reused by many selectors. In sass, you can define a mixin for a common CSS style, and then call the defined mixin directly where you want to use those styles. Of course the most powerful part of Mixin is that it can pass parameters.

Sass when declaring a mixins, and@mixinthen followed by the name of Mixins, he can also define parameters, and you can set a default value for this parameter, but the parameter name begins with a$symbol, and the parameter value needs to be separated by a colon (:). Multiple parameters are separated by commas. There is another situation here, that is, if a property value can have multiple values, such as Box-shadow and transition, then our arguments can be represented by a variable name plus three dots, such as$variables....




Declaration Mixins (@mixin)


Mixin opacity default transparency is 50% @mixin opacity ($opacity: m) {   opacity: $opacity/100;   
Box-shadow can have more than one value, so add after the variable argument ... @mixin box-shadow ($shadow ...) {   -moz-box-shadow: $shadow;   


Call Mixins (@include)



The mixins that is defined in the selector call needs to be used and@includethen immediately followed by the Mixins name to invoke. If you use the default parameter values, you can omit the parentheses.



. opacity{   @include opacity; opacity-80{   
. box{   border:1px solid #ccc;  

#logo {   @include box-shadow (0 5px 5px Rgba (0,0,0,.3));   &:hover{     @include opacity   }}  

. opacity{   opacity:0.5;   Filter:alpha (OPACITY=50); }
. opacity-80{   opacity:0.8;   Filter:alpha (opacity=80); }
. box{   border:1px solid #ccc;   -moz-box-shadow:0 2px 2px Rgba (0,0,0,.3), 0 3px 3px Rgba (0,0,0,.3), 0 4px 4px Rgba (0,0,0,.3);
   
#logo {   
  box-shadow:0 5px 5px Rgba (0,0,0,.3); }
#logo: hover{   opacity:0.5;   


As can be seen from the above example: 1, opacity and logo hover are called@include opacity;, but the parsed style does not combine the declaration; 2, Box-shadow this mixin uses a variable followed by three points to pass the argument, to apply it can declare multiple values.



@content



It is also the emergence of CSS3 bring some trouble, and @content is introduced from the sass3.2.0 to solve the CSS3 @media style trouble. It allows Mixin to accept an entire block of styles, and the accepted style begins with the @content.


Sass Style//-------------------------------                      
@mixin Max-screen ($res) {@media only screen and   (max-width: $res)   {     @content;   }}  
@include Max-screen (480px) {body   {color:red}}}  
@media only screens and (max-width:480px) {body   {color:red}}}                      


The style defined by Ps:mixin, the style that is parsed through the @include invocation, exists as a copy, and the following inheritance exists in the form of a joint declaration, so after the 3.2.0 version, it is recommended that you pass the parameter's mixin instead of passing the argument class using the following inheritance



Inherited

In Sass, selector inheritance allows the selector to inherit all the styles of another selector and joint declarations. Using the selector inheritance, use the keyword@extend, followed by the selector you want to inherit.

 
h1{   
. speaker{   @extend H1;   border-width:2px; }  
 
h1,.speaker{   
. speaker{   




Placeholder Selector



Since Sass 3.2.0 can be defined as a placeholder selector%, the advantage of this selector is that if you do not call then you will not have any extra CSS files, avoiding the previously predefined styles in some underlying files, Then the actual application, regardless of whether or not to use the extend to inherit the corresponding style, will parse out all the styles. Placeholder selector for%logo definition, direct with name


Sass Style//-------------------------------
%ir{   color:transparent;   Text-shadow:none;   Background-color:transparent;   
%clearfix{   @if $lte 7 {     *zoom:1   }   &:before,   
&:after {     content: "";     display:table;     Font:0/0 A;   }   &:after {     clear:both;   
#header {   h1{     @extend%ir;     width:300px;   
. ir{   

#header H1, ir{   color:transparent;   Text-shadow:none;   Background-color:transparent;   
#header h1{   


As on the code, defines two placeholder selectors%irand%clearfix, where clearfix this does not call, so the parsed CSS style also has no clearfix part. The appearance of the placeholder selector makes the CSS file more concise and controllable, no redundancy. So when you want to define some basic style files later, you can use a placeholder selector.



Operation

Sass has the characteristic of operation, it can subtraction arithmetic for numerical typeValue(such as: number, color, variable, etc.). Note that you leave a space before and after the operator, or you will get an error.

$baseFontSize:          14px!default $baseLineHeight:        1.5!default; $baseGap:
               $baseFontSize * $baseLineHeight!default; $HALFBASEGAP:           
$BASEGAP/2  !default $samllFontSize:         $baseFontSize -2px  !default;  
Grid  $_columns:                     !default;      
Total number of columns $_column-width:                60px!default;   
Width of a single column $_gutter:                      20px!default;     
Width of the Gutter $_gridsystem-width:            
 



Function


Sass defines a number of functions to use, and of course you can define your own functions to start with @fuction. Sass's official function link is: Sass fuction, the actual project we use the most should be the color function, but in the color function with Dodgelightenanddarkendeepen as the most, its invocation method islighten($color,$amount)anddarken($color,$amount), their first parameter is the color value, The second parameter is a percentage.


Sass Style//-------------------------------                      
$baseFontSize:      10px!default; $gray:              
#ccc!defualt;          
Pixels to Rems  @function Pxtorem ($px) {   @return $px/$baseFontSize * 1REM;}  
body{   font-size: $baseFontSize;   
. test{   Font-size:pxtorem (16px);   Color:darken ($gray, 10%);}  

body{   font-size:10px;   Color: #E6E6E6; }. test{   Font-size:1.6rem;   Color: #B3B3B3; }


About the color function can be mentioned above sass Fuction in front of a few are color aspects of the function, divided into Rgba FUNCTIONS,HSL functions,opacity functions,other color functions. Suggest other functions can be under the browser, probably understand that there is such a thing, later can be easily consulted.




Variable Range

Sass's range of variables is easily confusing, in a word--if you define a global variable and then overwrite it in a selector, then all subsequent variables are the overridden value. If there is no definition in the global, only a variable is defined in the selector, and the outside is not callable. Another special case is a variable that has the default value of!default, it will first find whether the global redefined, if not the use of default values, if any, use a redefined value.

 
. test{   $color: red;   Color: $color; }. test2{   color: $color;}  
CSS style//-------------------------------. Test {   color:red;  } test2 {   color:red;  

As you can see from the above, $color redefined in test, the test2 is a redefined value, that is, when the $color of the global variable passes the local definition in test, the value changes. This is what many people call sass without global variables and local variables, of course not. Here will give you a detailed answer: Sass variable default scope




Other



Conditional judgment



@ifOne condition can be used alone, can also be@elseused in combination with multiple conditions


Sass Style//-------------------------------
$type: Monster; p {   @if $type = = Ocean {     color:blue   } @else if $type = = Matador {     color:red;   }
@else if $type = = Monster {     color:green   } @else {     color:black;   
CSS style//-------------------------------p {   Color:green  }


For loop



The For Loop has two forms:@for $var from <start> through <end>and@for $var from <start> to <end>. $i represents a variable, start represents the starting value, and end represents the ending value, which is the difference between the keyword through indicating that the number is included, and the to does not include this number.



@for $i from 1 through 3 {   

. item-1 {   width:2em  }
. item-2 {   width:4em  }. item-3 {   width:6em;  }


Judgement of three eyes in sass



if($condition, $if_true, $if_false), three parameters represent the condition, the condition is true, and the condition is a false value.


if (true, 1px, 2px) => 1px if (false, 1px, 2px) => 2px


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.