How preprocessor sass is used

Source: Internet
Author: User
Tags map data structure variable scope
This time for you to bring the preprocessor sass how to use, the use of pre-processor Sass considerations, the following is the actual case, together to see.

Sass is an enhanced CSS helper that adds advanced features such as variables (variables), nesting (nested rules), blending (mixins), and import (inline imports) on top of CSS syntax to make CSS more powerful With elegance. Using the Sass and Sass style libraries, such as Compass, helps to better organize style files and develop projects more efficiently.

1. Featured Features

    1. Fully compatible with CSS3

    2. Add functions such as variables, nesting (nesting), and blending (Mixins) based on CSS

    3. Operation of color value and attribute value by function

    4. Provides advanced features such as control directives

    5. Custom output formats

file suffix name:sass has two suffix name files, one suffix named sass, no curly braces and semicolons, and the other is the Scss file we use here, similar to the CSS file format we normally write, using curly braces and semicolons. All of the Sass files described in this tutorial refer to files with the suffix named Scss. It is also recommended to use a file with the suffix named Scss to avoid the strict formatting requirements for sass suffix names.

File suffix named sass syntax body  background: #eee  font-size:12pxp  background: #0982c1//file suffix named Scss syntax  Body {  background: #eee;  font-size:12px;} p{  background: #0982c1;}

2. Sass and less syntax comparison

The difference between 2.1 sass and less

    1. The compilation environment is different--sass based on a server-side environment such as Ruby, less can support both server-side compilation and client (browser environment) compilation

    2. Variables are different--sass use the $ symbol to declare variables, less uses the @ sign to declare variables

    3. Support for conditional statements is not the same--sass supports complex conditional statements (similar to if: else.. ), less supports only simple conditional statements (similar to if ()).

    4. Scope--sass Locally modified variables can affect global variables, and less will only take effect at local scope.

    5. Referring to external CSS files in different ways--sass default when introducing. Sass or. scss files, and less requires a keyword configuration to control how the incoming file is handled.

2.2 Sass in a similar place to less

    1. Mixed (mixins)--similar to a function or macro, and can pass parameters;

    2. Nested rules are nested in the--class class, thus reducing duplication of code;

    3. In operation--css, various values and strings are calculated using subtraction.

    4. Color function--You can edit the color through the built-in function;

    5. Namespaces (namespace)--grouping styles, which can be called;

3. Sass Grammar Main Function Introduction

3.1 CSS Feature extensions

Nesting rules

Sass allows a set of CSS styles to be nested into another set of styles, with the inner layer's selector as the parent selector, the nesting feature avoids the repetition of the parent selector, and makes the complex CSS structure easier to manage, for example:

Sass style or less style#main p {  color: #00ff00;  width:97%;  . Redbox {    background-color: #ff0000;    Color: #000000;  }} CSS Style#main p {color: #00ff00; width:97%;} #main P. Redbox {  background-color: #ff0000;  Color: #000000; }

Parent Selector &

When nesting CSS rules, it is sometimes necessary to use the parent selector of the nested outer layer directly, for example, when you set the hover style for an element, or when the BODY element has a classname, you can use & to represent the parent selector of the nested rule's outer layer.

Sass Style or less Stylea {  font-weight:bold;  Text-decoration:none;  &:hover {text-decoration:underline;}  Body.firefox & {font-weight:normal;}} CSS Stylea {font-weight:bold;text-decoration:none;} a:hover {  text-decoration:underline;} Body.firefox a {  font-weight:normal;}

Property nesting

Some CSS properties follow the same namespace (namespace), such as font-family, Font-size, and font-weight all use the font as the namespace of the property. To facilitate the management of such properties, and also to avoid duplicate input, Sass allows attributes to be nested in namespaces, for example:

Sass Style.funky {  font: {    family:fantasy;    Size:30em;    Weight:bold;}  } CSS Style.funky {  font-family:fantasy;  Font-size:30em;  Font-weight:bold; }

A namespace can also contain its own property values, such as:

Sass Style.funky {  font:20px/24px {    family:fantasy;    Weight:bold;}  } CSS Style.funky {  font:20px/24px;    Font-family:fantasy;    Font-weight:bold; }

3.2 Import

The Sass Import (@import) rule differs from CSS in that the @import scss file is merged in to generate only one CSS file. However, if you import CSS files in the Sass file, such as @import ' reset.css ', the effect is the same as the normal CSS import style file, the imported CSS file will not be merged into the compiled file, but in @import way.

All Sass import files can ignore the suffix name. Scss. Generally speaking, the underlying file naming method begins with _, such as _mixin.scss. This kind of file can not be underlined when importing, can write @import "Mixin".

Less import (@import) syntax: @import (keyword) "filename";

Multiple keywords @import are allowed, you must use commas to separate the keywords: example: @import (optional, reference) "Foo.less";

    1. Reference: Use the less file but do not export it

    2. Inline: Includes output in source file, but not processed

    3. Less: Treats the file as a less file, regardless of its extension

    4. CSS: Treats a file as a CSS file, regardless of the extension

    5. Once: The file can only be imported once (default)

    6. Multiple: The file can be imported multiple times

    7. Optional: Still compiles when no files are found

Sample import File Code:

/* is imported SASS file A.scss,less file a.less:*///a.scss or a.less//-------------------------------body {  background: #eee;} /* Sass file to import style b.scss,less file b.less:*/@import "reset.css"; @import "a";p {  background: #0982c1;}   /* Translated B.CSS style: */@import "reset.css"; body {  background: #eee;} p{  background: #0982c1;}

As you can see from the code above, B.scss compiles, RESET.CSS continues to keep the import, and a.scss is integrated. Similarly, less is handled in less.

3.3 Comments/* */with//

Sass supports the standard CSS multiline comment/* */, and the single-line comment//, which is fully output to the compiled CSS file, while the latter does not. Don't worry about this in less, more than one line of comments/*/and single-line comments//can be used at will, and are preserved during compilation. For example:

Sass style/* This comment is * several lines long. * Since it uses the CSS comment syntax, * It'll appear in the CSS output. */body {color:black;} These comments is only one line long each.//they won ' t appear on the CSS output,//since they use the Single-line com ment syntax.a {color:green;} CSS style/* This comment is * several lines long. * Since it uses the CSS comment syntax, * It'll appear in the CSS output. */body {  color:black;} a {  color:green;}

3.4 Sassscript

Variable $

The SASS variable must be a $ start, followed by the variable name, and a default value if the value is appended with!default. The variables for less are similar to sass, but use symbols differently, less uses the @

Sass style//-------------------------------$fontSize: 12px;body{    font-size: $fontSize;}  Less style//-------------------------------@fontSize: 12px;body{    font-size: @fontSize;} CSS style//-------------------------------body{    font-size:12px;}

Variable default value

The default variables for sass are generally used to set default values and then overwrite them as required, and the way to overwrite them is simple, just to re-declare the variables before using the default variables; The value of the default variable is very useful for component development.

Sass style//-------------------------------$baseLineHeight:  1.5!default;body{    line-height: $ Baselineheight; }//css style//-------------------------------body{    line-height:1.5;} /* Override default value *///sass style//-------------------------------$baseLineHeight:  2; $baseLineHeight:  1.5!default; body{    line-height: $baseLineHeight;} CSS style//-------------------------------body{    line-height:2;}

The use form of variable #{}

In general, the variables we define are attribute values that can be used directly, but must be used as #{$variables} If the variable is a property or, in some special cases, inferior.

Sass style//-------------------------------$borderDirection:    top!default; $baseFontSize:       12px!default; $baseLineHeight:     1.5!default;//applies to class and attributes. border-#{$borderDirection} {  border-#{$borderDirection}:1px Solid #ccc;} Applied to complex attribute values body{    font:#{$baseFontSize}/#{$baseLineHeight};} CSS style//-------------------------------. border-top{  border-top:1px solid #ccc;} body {  font:12px/1.5;}

Multi-valued Variable list

Simply put, the list type is a bit like an array in JS. The list data can be separated by spaces, commas, or parentheses, using nth ($var, $index) values.

There are many other functions for list data operations such as length ($list), join ($list 1, $list 2,[$separator]), append ($list, $value, [$separator]), etc.

Defined:

One-dimensional data $px:5px 10px 20px 30px;//Two-dimensional data, equivalent to JS in the two-dimensional array $px:5px 10px, 20px 30px, $px: (5px 10px) (20px 30px);

How to use:

Sass style//-------------------------------$linkColor:  #08c #333!default;//The first value is the default and the second mouse over value a{  color: Nth ($linkColor, 1);  &:hover{    Color:nth ($linkColor, 2);}  } CSS style//-------------------------------a{  color: #08c;} a:hover{  color: #333;}

Multi-valued variable map

Simply put, the map type is somewhat like the map data structure in the ES6 syntax. The map data appears in pairs of key and value, where value can be a list.

The format is: $map: (key1:value1, Key2:value2, key3:value3); values can be obtained by Map-get ($map, $key). There are many other functions for map data such as Map-merge ($map 1, $map 2), Map-keys ($map), Map-values ($MAP), etc.

Defined:

$heading: (H1:2em, H2:1.5em, H3:1.2EM);

How to use:

Sass style//-------------------------------$headings: (H1:2em, H2:1.5em, H3:1.2em), @each $header, $size in $headings {  #{$header} {    font-size: $size;  }} CSS style//-------------------------------h1 {  font-size:2em;} h2 {  font-size:1.5em;} h3 {  font-size:1.2em;}

Variable scope

The variable scopes in sass and less are similar to the two variables declared in JavaScript, and the following code compares the different ways of handling variable declarations.

The variable assignment in sass directly modifies the global variable, and the variable assignment in less can only be applied locally.

Sass style$color:red; p{   $color: blue;   Color: $color;//blue} a{   color: $color;//blue}//less style@color:red; p{   @color: blue;   Color: @color;//blue} a{   color: @color;//red}

3.5 Mixing (Mixin)

Sass Use @mixin to declare a blend, you can pass parameters, or you can set a default value for a parameter. The declared @mixin is called by @include, and in less it is only required to refer directly to the defined class in a similar way to a function.

No parameter mixin

Sass Style@mixin Center-block {    margin-left:auto;    Margin-right:auto;}. demo{    @include Center-block;} Less style.center-block {    margin-left:auto;    Margin-right:auto;}. demo{    . Center-block;} CSS style.demo{    margin-left:auto;    Margin-right:auto;}

With parameter mixin

Sass Style@mixin Opacity ($opacity:) {  opacity: $opacity/100;  Filter:alpha (opacity= $opacity);}. opacity-80{  @include opacity (80);//Pass Parameters}//less style.opacity (@opacity:) {  opacity: @opacity/100;  Filter:alpha (opacity= @opacity);}. opacity-80{  . Opacity (80);//Pass Parameters}//css style.opacity-80{  opacity:. 8;  Filter:alpha (opacity=80);}

Multiple parameter Mixin

Sass call can pass directly to the value, such as the number of @include passed in the parameter is less than the number of @mixin defined parameters, then in order, the following insufficient use of the default value, such as insufficient no default value error. In addition, you can optionally pass in parameters, use parameter names and values at the same time; less uses similar methods.

Sass Style   @mixin horizontal-line ($border: 1px dashed #ccc, $padding: 10px) {    border-bottom: $border;    Padding-top: $padding;    Padding-bottom: $padding;  }. Imgtext-h li{    @include horizontal-line (1px solid #ccc);} Less style.horizontal-line (@border: 1px dashed #ccc, @padding: 10px) {    border-bottom: @border;    Padding-top: @padding;    Padding-bottom: @padding;  }. Imgtext-h li{    . Horizontal-line (1px solid #ccc);} CSS style.imgtext-h li {    border-bottom:1px solid #cccccc;    padding-top:10px;    padding-bottom:10px;}

Multi-Set Value parameter Mixin

Sass If a parameter can have more than one set of values, such as Box-shadow, transition, and so on, then the parameters need to add three points after the variable, such as $variables ... Less means you can use it directly when you have an indeterminate parameter ... Representing all parameters with @arguments

Sass Style   //box-shadow can have multiple sets of values, so add after variable arguments ... @mixin box-shadow ($shadow ...) {  -webkit-box-shadow: $shadow;  Box-shadow: $shadow;}. box{  border:1px solid #ccc;  @include 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));} Less Style.box-shadow (...) {  -webkit-box-shadow: @arguments;  Box-shadow: @arguments;}. box{  border:1px solid #ccc;  . 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));} CSS style.box{  border:1px solid #ccc;  -webkit-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);  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);}

3.6 Arithmetic

Sass has the characteristic of arithmetic, can subtraction arithmetic to numeric value (for example: number, color, variable, string, etc.). Note that you leave a space before or after the operator, or you will get an error.

Calculated value, variable $basefontsize:          14px!default; $baseLineHeight:        2!default; $BASEGAP:               $baseFontSize * $ Baselineheight!default; = 28px$halfbasegap:           $baseGap/4  !default;//= 7px$samllfontsize:         $baseFontSize -2px  ! Default = 12px$_columns:              !default;  $_column-width:         60px!default;  $_gutter:               20px!default;     $_gridsystem-width:     $_columns * ($_column-width + $_gutter);//= 960px//calculates the color p {  color: #010203 + #040506; /= #050709}//Compute string P:before {  content: "Foo" + Bar; = "Foo Bar"  font-family:sans-+ "serif";//= = Sans-serif}

3.7 Control Instructions

Sassscript provides some basic control instructions, such as referencing a style when certain conditions are met, or setting the range repeating output format. Control directives are an advanced feature that is not commonly used during routine writing, and is used primarily in conjunction with mixed instructions (mixin).

@if

Sass Stylep {  @if 1 + 1 = = 2 {border:1px solid;}  @if 5 < 3 {border:2px dotted;}  @if null  {border:3px double;}} CSS Stylep {border:1px solid;} 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;  }} Less style@type:monster;p (@type) when (@type = Ocean) {color:blue;} P (@type) when (@type = Matador) {color:red;} P (@type) when (@type = monster) {Color:green;} P (@type) when (@type = dark) {color:black;} CSS Stylep {color:green;}

@for

The @for directive consists of two formats: @for $var from <start> through <end>, or @for $var from <start> to <end> the difference is through Meaning with to: when using through, the condition range contains the values of <start> and <end>, while using to the condition range contains only <start> values that do not contain <end> values. In addition, $var can be any variable, such as $i;<start> and <end> must be an integer value.

Sass Style@for $i from 1 through 3 {  . item-#{$i} {width:2em * $i;}} CSS style.item-1 {  width:2em;}. item-2 {  width:4em;}. item-3 {  width:6em;}

@each

The syntax is: @each $var in <list or map>. Where $var represents variables, and list and map represent the list type data and map type data.

Single Field list data loop:

Sass Style$animal-list:puma, Sea-slug, Egret, Salamander; @each $animal in $animal-list {  . #{$animal}-icon {    Background-image:url ('/images/#{$animal}.png ');}  } CSS Style.puma-icon {  background-image:url ('/images/puma.png ');}. Sea-slug-icon {  background-image:url ('/images/sea-slug.png ');}. Egret-icon {  background-image:url ('/images/egret.png ');}. Salamander-icon {  background-image:url ('/images/salamander.png ');}

Multiple fields list data loop:

Sass style//-------------------------------$animal-data: (Puma, black, default), (Sea-slug, blue, pointer), (Egret, White, move), @each $animal, $color, $cursor in $animal-data {  . #{$animal}-icon {    background-image:url ('/images /#{$animal}.png ');    border:2px solid $color;    cursor: $cursor;  }} CSS style//-------------------------------. 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; }

Multiple fields map data loop:

Sass style//-------------------------------$headings: (H1:2em, H2:1.5em, H3:1.2em), @each $header, $size in $headings {  #{$header} {    font-size: $size;  }} CSS style//-------------------------------h1 {  font-size:2em;} h2 {  font-size:1.5em;} h3 {  font-size:1.2em;}

@extend

The function of the @extend is to extend the reused style (. Error) (extend) to a special style (. Seriouserror) that needs to contain this style, as an example:

Sass style//-------------------------------. Error {  border:1px #f00;  Background-color: #fdd;}. error.intrusion {  Background-image:url ("/image/hacked.png");}. Seriouserror {  @extend. Error;  border-width:3px;} CSS style//-------------------------------. error,. seriouserror {  border:1px #f00;  Background-color: #fdd; }.error.intrusion,. seriouserror.intrusion {  background-image:url ("/image/hacked.png");}. seriouserror {  border-width:3px;}

3.8 function Instructions

Sass supports custom functions and can be used in any attribute value or Sass script:

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

As with Mixin, you can also pass several global variables to a function as a parameter. A function can contain multiple statements that need to be called @return output results.

The Sass function allows the use of keyword parameters, the above example can also be written as:

Keyword parameter call form #sidebar {width:grid-width ($n: 5);}

Although not concise enough, it is easier to read. Keyword parameters give functions a more flexible interface, as well as easy-to-invoke parameters. Keyword parameters can be scrambled to use, if the default value can also be saved, in addition, parameter names are treated as variable names, underscores, dashes can be used interchangeably.

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

How to realize the caterpillar crawling animation

Redraw and rearrange how to use

Canvas animation for rotating Tai Chi

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.