Documentation

Sass is a CSS extension that allows you to use variables , nested rules , mixins , inline imports and other functions based on CSS syntax to make CSS more powerful and elegant.. Using Sass and the Compass style library can help better organize and manage style files and develop projects more efficiently.

Features

  • Fully compatible with CSS3
  • Adding variables, nesting, mixins and other functions to the CSS language
  • Calculation of color and attribute values ​​through functions
  • Provide control instructions and other advanced features
  • Custom output format

Syntax

Sass has two syntax formats. The first is SCSS (Sassy CSS), which is also the format used in this reference example. This format is only extended based on CSS3 syntax, which means that each CSS style sheet is an equivalent SCSS file. In addition, SCSS also supports most CSS hacks writing browser-specific prefixes and syntax (vendor-specific syntax), for example, IE ancient filtergrammar . This syntax style sheet files need to be .scssas expand the name.

The other, the earliest syntax, is called Indented Sass, or "Sass", which provides a more introductory way to write CSS. It uses indentation instead of curly braces to indicate selector nesting, and uses line breaks instead of semicolons to separate attributes. Some people think this is easier to read and faster to write than SCSS. The indented syntax has all the features of Sass, although there are slight differences in syntax ; the specific differences are described in the indented syntax reference . Use this syntax style sheet file needs to .sassextension.

Files of any syntax can be imported directly into files of another syntax, as long as you use the sass-convert command line tool, you can convert one syntax to another:

# Convert Sass to SCSS
  $ sass-convert style.sass style.scss
  
  # Convert SCSS to Sass
  $ sass-convert style.scss style.ss
  

Note that this command does not generate a CSS file. To generate CSS files, use described elsewhere sasscommand.

Using Sass (Using Sass)

Sass can be used in three ways: as a command line tool, as a standalone Ruby module, or as a plug-in to the Rack-enabled framework, including Ruby on Rails and Merb. Either way, you need to install the Sass gem first:

gem install sass
  

If you are using Windows, you may first need to install Ruby .

If you want to run Sass from the command line, just use

sass input.scss output.css
  

You can also use Sass commands to monitor changes in a Sass file and automatically compile to update CSS:

sass --watch input.scss:output.css
  

If you have many Sass files in your directory, you can also use Sass commands to monitor the entire directory:

sass --watch app/sass:public/stylesheets
  

Use sass --helpcan list the full help documentation.

Using Sass in Ruby is also very easy. After the Sass gem is installed, run it require "sass", and then use Sass :: Engine as follows:

engine = Sass::Engine.new("#main {background-color: #0000ff}", :syntax => :scss)
  engine.render #=> "#main { background-color: #0000ff; }\n"
  

Rack / Rails / Merb plugin (Plugin)

To enable Sass in versions prior to Rails 3, you need to add a line of code to the environment.rb file:

config.gem "sass"
  

For Rails 3, add this line to the Gemfile:

gem "sass"
  

To enable Sass in Merb, it is necessary config/dependencies.rbto add a line of code file:

dependency "merb-haml"
  

Sass is enabled in the Rack application, you need to config.ruadd the following code file:

require 'sass/plugin/rack'
  use Sass::Plugin::Rack
  

Sass stylesheets work differently from views. It does not contain any dynamic content, so it only needs to generate CSS when the Sass file is updated. By default, .sassand the .scssfile is placed (This can be done in a public / stylesheets / sass directory :template_locationconfigured options). Then, when needed, they are compiled into corresponding CSS files and placed in the public / stylesheets directory. For example, the public / stylesheets / sass / main.scss file will be compiled into the public / stylesheets / main.css file.

Caching

By default, the template (Template) after Sass cached automatically compiled and partials , doing so can significantly improve recompilation speed processing Sass the template is cut into a plurality of files and by @importeffect is particularly remarkable when the introduction, form a large file .

If the case does not use frames, Sass will be put into the template cache .sass-cachedirectory. In Rails and Merb, cached templates are placed in tmp/sass-cachedirectories. This directory can be :cache_locationcustomized with options. If you do not want Sass caching feature is enabled, you can :cacheoption to false.

Configuration options

Options can be set through the Sass :: Plugin # options hash, specifically set in Rails environment.rbor in config.rua file in Rack :

Sass::Plugin.options[:style] = :compact
  

Alternatively, if you use Merb, you can init.rbset a Merb::Plugin.config[:sass]hash in the file :

Merb::Plugin.config[:sass][:style] = :compact
  

Or by passing an option (options) hash to Sass :: Engine # the initialize ,
all relevant options are also available through labeling sassand scssuse the command-line executable file. Available options are:

Option description
: style Set the code style of the output CSS. You can view the output code style .
: syntax The syntax of the input file, which :sassmeans indented syntax, and :scssCSS extended syntax. Only useful if you construct a Sass :: Engine instance yourself ; when you use Sass :: Plugin , it will automatically set the correct value. The default setting is :sass.
: property_syntax The mandatory indent syntax document uses a property syntax. If the correct syntax is not used, an error will be thrown. :newA value indicates that a colon is mandatory after the attribute name. For example: color: #0f3or width: $main_width. :oldA value indicates that a colon is required before the attribute name. For example: :color #0f3or :width $main_width. By default, both syntaxes are valid. This option .scssis not valid for SCSS ( ) documents.
: cache Whether Sass should be cached when parsing, allowing faster compilation speed. The default setting is true.
: read_cache If this option is set and no :cacheoption is set , then the cache exists and the Sass cache is read-only. If there is no cache, it will not compile.
: cache_store If this option is set to an instance of a subclass of Sass :: CacheStores :: Base , the cache store will be used to store and retrieve cached compilation results. The default setting is Sass :: CacheStores :: Filesystem and the :cache_locationoption is initialized .
: never_update The CSS file should never be updated, even if the template file changes. Setting it to truemay result in small performance improvements. It always defaults to false. This option is only meaningful in Rack, Ruby on Rails, or Merb.
: always_update CSS files should always be updated, even when each controller is accessed, not just when the template is modified. The default is false. This option is only meaningful in Rack, Ruby on Rails, or Merb.
: always_check Sass templates should always be checked for updates, even when each controller is accessed, not just when the service starts. If a Sass template is updated, it will be recompiled and the corresponding CSS file will be overwritten. Default in production mode false, otherwise true. This option is only meaningful in Rack, Ruby on Rails, or Merb.
: poll If so true, always use Sass :: Plugin :: Compiler # watch backend polling instead of the backend of the native file system.
: full_exception Whether the errors in the Sass code should provide a detailed description in the generated CSS file. If set to true, this error will be displayed in the comments of the CSS file and at the top of the page (supported browsers). The error content includes line numbers and source code snippets. Otherwise, exceptions will be alerted in Ruby code. Default in production mode false, otherwise true.
: template_location A path to the directory of the Sass template in the root directory. If hashed, :css_locationit is ignored and this option specifies the mapping between the input and output directories. A binary list can also be given instead of a hash. The default is css_location + "/sass". This option is only meaningful in Rack, Ruby on Rails, or Merb. Note that if multiple template locations are specified, they are all placed in the import path, allowing you to import between them.
It should be noted that since it can take many possible formats, this option should only be set directly and should not be accessed or modified. Use Sass :: Plugin # template_location_array , Sass :: Plugin # add_template_location , Sass :: Plugin # remove_template_location methods instead.
: css_location The path of the CSS file output. When the :template_locationoption is a hash, this option will be ignored. The default setting is "./public/stylesheets". This option is only meaningful in Rack, Ruby on Rails, or Merb.
: cache_location Among them, sasscthe path where the cache file should be written. Defaults in Rails and Merb "./tmp/sass-cache", otherwise defaults "./.sass-cache". If the :cache_storeoption is set , this will be ignored.
: unix_newlines If true, use Unix-style newlines when writing files. Only meaningful on Windows and only when Sass is written to a file (in Rack, Rails, or Merb, when using Sass :: Plugin directly , or when using a command line executable).
: filename The file name of the rendered file. This is completely for reporting errors and is set automatically when using Rack, Rails, or Merb.
: line The line number of the first line of the Sass template. The line number used to report the error. This setting is useful if the Sass template is embedded in a Ruby file.
: load_paths An array containing the file system or @importSass template paths imported via directives. They may be strings, Pathname(pathname) objects, or subclasses of Sass :: Importers :: Base . This option defaults to the working directory, and in Rack, Rails, or Merb, this option has any value :template_location. Load path may also be made Sass.load_paths and SASS_PATHinform the environment variables.
: filesystem_importer A subclass of Sass :: Importers :: Base to handle the loading path of ordinary strings. This should import files from the file system. This should be a Class object that takes a string parameter (load path) via the constructor and inherits from Sass :: Importers :: Base . The default is Sass :: Importers :: Filesystem .
: sourcemap Controls how sourcemaps are produced. These sourcemaps tell the browser how to find Sass styles and generate each CSS style. This option has three valid values: :autouse relative URIs where possible, assuming source styles are provided on any server you use, their relative positions will be the same as the local file system. If a relative URI is not available, it will be replaced by "file:". :fileAlways use the "file:" URI, which will work locally but cannot be deployed to a remote server. :inlineContains the complete source text from the sourcemap. This is most convenient, but may produce very large sourcemap files. In the end, the :nonesourcemap file is never generated.
: line_numbers When set to true, the line number and file name of the defined selector will be injected as comments into the compiled CSS. This is useful for debugging, especially when using @importsum @mixin. This option has a specific name :line_comments. When using the :compressedoutput style or use :debug_info/ :trace_selectorsoption This option is automatically disabled.
: trace_selectors When set to true, the full trajectory of @importsum will be injected before each selector @mixin. This is useful when debugging passed @importand @mixinincluded style sheets in the browser . This option will replace :line_commentsoption, and is :debug_infothe option to replace. When :compressedthe output style, this option is automatically disabled.
: debug_info When set to true, the line number and file name of the defined selector will be injected into the compiled CSS and recognized by the browser. Used for FireSass Firebug extension to display Sass file names and line numbers. When :compressedthe output style, this option is automatically disabled.
: custom This option can be used for individual application settings to make the data available for custom Sass functionality .
: quiet When set to true, causes warning messages to be disabled.

Syntax Selection

The Sass command line tool will use the file extension to determine which syntax you are using, but it is not always a file name. sassThe command line program defaults to indented syntax, but if the input should be parsed into SCSS syntax, you can pass --scssoptions to her. In addition, you can use the scsscommand line program, which sassis exactly the same as the program, but its default syntax is SCSS.

Encodings

When running Sass in Ruby 1.9 and above, Sass is sensitive to the encoding format of the file. First, it will determine the encoding format of the style file according to the CSS spec . If it fails, it will detect the Ruby string encoding. That is, first check Sass Unicode byte order mark, then the @charsetstatement is the last string code Ruby, if not detected, use the default UTF-8 encoding.

To explicitly specify the encoding of the style sheet, as with CSS, use @charsetdeclarations. Insert it at the beginning of the style file (without any whitespace and comments) @charset "encoding-name";, and Sass will compile the file with the given encoding format. Note that no matter what encoding you use, it must be convertible to the Unicode character set.

By default, Sass always outputs CSS files in UTF-8 encoding. If and only if the output file contains non-ASCII characters in the output file will be added to @charsetdeclare, in the compressed mode, the (compressed mode) using UTF-8 byte order mark instead of @charset declaration statement in a compressed mode.

CSS extensions

Nested rules

Sass allows you to nest a CSS style into another style. The inner style is only applicable to the selector of the outer style (note: it can be understood as a level selector). For example:

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

Compiles to:

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

This helps avoid parent selector duplication, which is much simpler than multi-level nested selectors in complex CSS layouts. E.g:

#main {
    width: 97%;
  
    p, div {
      font-size: 2em;
      a { font-weight: bold; }
    }
  
    pre { font-size: 3em; }
  }
  

Compiles to:

#main {
    width: 97%; }
    #main p, #main div {
      font-size: 2em; }
      #main p a, #main div a {
        font-weight: bold; }
    #main pre {
      font-size: 3em; }
  

Reference Parent Selectors: &

Sometimes the need for direct use nested outer parent selector, this is very useful, for example, you might like to selectors hover styles, or when the body has a style element, in these cases, you can &Character To explicitly insert the specified parent selector. E.g:

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

Compiles to:

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

&Will be replaced with the parent selector rendered in the CSS file. This means that if you have a multi-level nested rule, the parent selector will be &completely decomposed before being replaced. E.g:

#main {
    color: black;
    a {
      font-weight: bold;
      &:hover { color: red; }
    }
  }
  

Compiles to:

#main {
    color: black; }
    #main a {
      font-weight: bold; }
      #main a:hover {
        color: red; }
  

&Must appear at the beginning of the selector (note: the first character as the selector), but can follow the suffix and will be added after the parent selection. E.g:

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

Compiles to:

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

Father selector &is used as a suffix of time, Sass will throw an error.

Nested properties

CSS has some attributes follow the same "namespace"; such as, font-family, font-size, and font-weightare in the fontnamespace. In CSS, if you want to set a bunch of properties in the same namespace, you have to output it every time. Sass provides a shortcut for this: you only need to enter the namespace once, and then nest the child attributes inside it. E.g:

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

Compiles to:

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

Namespaces can also have their own attribute values. E.g:

.funky {
    font: 20px/24px fantasy {
      weight: bold;
    }
  }
  

Compiles to:

.funky {
    font: 20px/24px fantasy;
      font-weight: bold;
  }
  

Placeholder selector: %foo(the Placeholder the Selectors: %foo)

Sass supports a special type of selector called a placeholder selector. These look like class and id selectors, except #or .by %replacement. They need to be used in @extenddirectives ; see @extend-Only Selectors for more information .

When they are used alone, that @extendis, unused, rule sets that use placeholder selectors will not be rendered as CSS.

Comments: /* */and //(Comments: /* */and //)

Sass supports standard CSS multi-line comments as /* */well as single-line comments //. Wherever possible, multi-line comments are retained in the output CSS, while single-line comments are deleted. E.g:

/* This comment is
   * several lines long.
   * since it uses the CSS comment syntax,
   * it will appear in the CSS output. */
  body { color: black; }
  
  // These comments are only one line long each.
  // They won't appear in the CSS output,
  // since they use the single-line comment syntax.
  a { color: green; }
  

Compiles to:

/* This comment is
   * several lines long.
   * since it uses the CSS comment syntax,
   * it will appear in the CSS output. */
  body {
    color: black; }
  
  a {
    color: green; }
  

If the first letter of a multi-line comment is !, the comment is always retained in the output CSS, even in compressed output mode. This can be used to add a copyright notice to your generated CSS.

Using interpolation, you can output variable values ​​into multi-line comments, for example:

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

Compiles to:

/* This CSS is generated by My Snazzy Framework version 1.2.3. */
  

SassScript

In addition to the syntax of ordinary CSS properties, Sass supports some extensions called SassScript. SassScript allows attributes to use variables, arithmetic and extra features. SassScript can be used on any property value.

SassScript can also be used to generate selectors and attribute names, which is very useful when writing mixins . This is done through interpolation .

Interactive shell

The Interactive Shell can test the functionality of SassScript from the command line. Enter sass -i on the command line, and then enter the SassScript you want to test to see the output:

You can easily try SassScript using the Interactive Shell.
To run the startup shell, just use the -ioption's sass command line (note: type in the command line sass -i).
At the prompt, enter any valid SassScript expression, which will evaluate and print your results elsewhere:

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

Variables: $(the $Variables: )

The most straightforward way to use SassScript is to use variables. Variables start with a dollar sign, and assignments are like setting CSS properties:

$width: 5em;
  

You can reference them in attributes:

#main {
    width: $width;
  }
  

Variables are available only within the scope of the selector nesting level it defines (note: can be understood as block-level scope). Variables that are not defined inside any nested selectors can be used anywhere (note: can be understood as global variables). When you define a variable, you can put a !globalflag behind it . In this case, the variable is visible everywhere (note: it can be understood as a global variable). E.g:

#main {
    $width: 5em !global;
        width: $width;
  }
  
  #sidebar {
    width: $width;
  }
  

Compiles to:

#main {
    width: 5em;
  }
  
  #sidebar {
    width: 5em;
  }
  

For historical reasons, variable names (and all other Sass identifiers) are interchangeable with hyphens (note:) -and underscores (note:) _. For example, if you define a named $main-widthyou can use to $main_widthaccess it, and vice versa.

Data Types

SassScript supports 7 main data types:

  • Numbers (e.g.: 1.2, 13, 10px)
  • Text strings, quoted strings and string without quotation marks (e.g.: "foo", 'bar', baz)
  • Color (e.g.,: blue, #04a3f9, rgba(255, 0, 0, 0.5))
  • Boolean value (for example: true, false)
  • Empty (for example: null)
  • Value list (List), or comma-separated by spaces (eg: 1.5em 1em 0 2em, Helvetica, Arial, sans-serif)
  • maps, a mapping from one value to another (for example: (key1: value1, key2: value2))

SassScript also supports CSS property values of all other types, such as Unicode character set, or !importanta statement. However, these types of attribute values ​​are not treated specially and are always treated as unquoted strings.

Strings

CSS specifies two types of strings: quoted strings (note: including double quotes and single quotes), such as "Lucida Grande"or 'http://sass-lang.com', and unquoted strings, such as sans-serifor bold. SassScript recognizes both types, and in general, the type of strings used in Sass documents is not changed in the compiled output CSS file.

With one exception, when using #{}interpolation , quoted strings will be compiled into unquoted strings, which is mainly for convenience, such as selector names in mixins . E.g:

@mixin firefox-message($selector) {
        body.firefox #{$selector}:before {
      content: "Hi, Firefox users!";
    }
  }
  
  @include firefox-message(".header");
  

Compiles to:

body.firefox .header:before {
    content: "Hi, Firefox users!"; }
  

Lists

List (lists) refers to how CSS Sass said in a statement, similar to margin: 10px 15px 0 0or font-face: Helvetica, Arial, sans-serifsuch values, a list of just a bunch of other values, whether or comma separated by a space. In fact, independent values ​​are also treated as lists: a list containing only one value.

The list itself doesn't have much functionality, but Sass list functions give the array more new features: the nth function can directly access an item in the array; the join function can connect multiple arrays together; the append function can be added to the array The new value; the @each directive is able to iterate through each item in the array.

The list itself doesn't have much functionality, but SassScript list functions make them very useful. nthFunctions can directly access an item in a list; joinfunctions can splice multiple lists together; appendfunctions can add an item to a list; @eachinstructions can add styles to each item in the list.

In addition to simple values, lists can contain other lists. For example, it 1px 2px, 5px 6pxcontains two items , 1px 2pxlist and 5px 6pxlist. If the inner and outer lists use the same delimiter, you need to use parentheses to enclose the inner list to specify where the inner categories begin and end.
For example, (1px 2px) (5px 6px)it is also a 1px 2pxlist containing 5px 6pxtwo items, list and list. The difference is that the outer layer of the list is separated by spaces. The outer layer of the previous list is separated by commas.

When the list is compiled into CSS, Sass does not add any parentheses because CSS does not recognize them. This means that, (1px 2px) (5px 6px)and 1px 2px 5px 6pxlooks exactly the same as in the CSS file compiled in. However, they are different in Sass: the first is a list with two lists, and the second is a list with four members.

Use () to represent an empty array containing no values ​​(also considered an empty map after Sass 3.3). Empty arrays cannot be compiled directly into CSS. For example, compiling font-family: () Sass will report an error. If the array contains empty arrays or empty values, it will be cleared at compile time, such as 1px 2px () 3px or 1px 2px null 3px.

Lists can also have no items. These lists can be ()expressed (also a empty the Map ).
They cannot be output directly to CSS; if you try to do so, for example font-family: (), Sass will report an error. If the list contains a null value or empty list, for example 1px 2px () 3px, or 1px 2px null 3px, before included in a list compiled CSS, empty list and a null value will be deleted.

A comma-separated list can retain trailing commas. This is particularly useful because it can represent a single element list.
For example, (1,)is represented as containing only 1a list, but (1 2 3,)this representation contains a list, the list also contains a space-delimited 1, 2and 3lists.

Maps

Maps represent a collection of key and value pairs, where keys are used to find values. They can easily collect values ​​into named groups and can access these groups dynamically. You can't find similar values ​​in CSS, although their syntax is similar to media query expressions:

$map: (key1: value1, key2: value2, key3: value3);
  

Unlike Lists, Maps must always be enclosed in parentheses and must be separated by commas. The keys and values ​​in Maps can be arbitrary SassScript objects. A Maps may have only one value associated with a given key (although the value can be a list). A given value may be associated with many keys.

Similar to Lists, Maps uses SassScript functions for its main operations . map-getFunctions are used to find the values ​​in the map. map-mergeFunctions are used to add values ​​to the map. @eachInstructions can be used to style each key-value pair in the map. The order of key-value pairs in a map is always the same as when the map was created.

Maps can also be used for anything that Lists can do. When used in a list function, map is treated as a list of key-value pairs. For example, (key1: value1, key2: value2)when used in a list function, it is treated as a nested list key1 value1, key2 value2. Lists cannot be considered maps, except for empty lists. ()Represents a map with no key / value pairs, and can also be considered a list with no elements.

Note that map keys can be of any Sass data type (or even another map), and the syntax for declaring maps is allowed to be any SassScript expression. This expression will be evaluated as a value to determine the key ( keys).

Maps cannot be converted to pure CSS. Passing a CSS function as the value or parameter of a variable will cause an error. Use inspect($value)functions to produce output strings, which is useful for debugging maps.

Colors

Any CSS color expression returns a SassScript color value. This includes a large number of named colors , these name strings are indistinguishable without quotation marks.

In compressed output mode, Sass will output short CSS color representations. For example, in the compressed mode #FF0000will be output red, but blanchedalmondthe output #FFEBCD.

A common problem a user encounters is that Sass likes to output the same format as the named colors in other output modes. When compressed, the colors interpolated to the selector become invalid syntax. To avoid this, always name the colors if they are intended to be used in the selection construction.

Operations

All data types support equality operations ( ==sum !=). In addition, each type has its own special arithmetic.

Number Operations

SassScript supports arithmetic operations on numbers (addition +, subtraction -, multiplication *, division, /and modulus %). Sass mathematical functions retain units during arithmetic operations. This means that, just like in real life, you cannot use different unit numbers for arithmetic operations (such as adding a pxsum emunit after the number), and multiplying two numbers with the same unit will produce a unit square ( 10px * 10px == 100px * px). Be aware that px * pxCSS units are invalid, and Sass will throw an error because you are trying to use invalid units in CSS.

Supports relational operators ( <, >, <=, >=), and supports all types of the equality operator ( ==, !=).

Division and /(Division and /)

CSS allows /occurs manner between the property value as a digital divider (Note: e.g. font attributes p.ex2{font:italic bold 12px/20px arial,sans-serif;}). Since SassScript is an extension of CSS attribute syntax, so it must support this, while also allowing /for the division. This means that, by default, if the two numbers in the SassScript /, will appear the same way in the separate return of the CSS.

However, there are /three cases that will resolve to division. These cover most cases of division. they are:

  1. If the value, or any part of the value, is stored in a variable or returned by a function.
  2. If the value is enclosed in parentheses, unless those brackets are outside a list and the value is inside the brackets.
  3. If the value is used as part of another arithmetic expression.

E.g:

p {
    font: 10px/8px;             // 原生的CSS,不作为除法
    $width: 1000px;
        width: $width/2;            // 使用了变量, 作为除法
    width: round(1.5)/2;        // 使用了函数, 作为除法
    height: (500px/2);          // 使用了括号, 作为除法
    margin-left: 5px + 8px/2px; // 使用了 +, 作为除法
    font: (italic bold 10px/8px); // 在一个列表(list)中,括号可以被忽略。
  }
  

Compiles to:

p {
    font: 10px/8px;
    width: 500px;
    height: 250px;
    margin-left: 9px; }
  

If you want pure CSS to /be used with variables (note: /not used as division), you can #{}insert them using . E.g:

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

Compiles to:

p {
    font: 12px/30px; }
  
Subtraction, negative, and -(Subtraction, a Numbers Negative, and -)

And in the Sass CSS -has many different meanings. It can be a subtraction operator (such as in 5px - 3px), a negative number (such as in -3px), a unary negative operator (such as in -$var), or a part of an identifier (such as in font-weight). Most of the time, we can easily tell -what exactly it represents, but there are some tricky treats. As a general rule, you are safest to use -:

  • Subtraction, you always -leave a space on both sides.
  • When representing a negative number or unary negative operation, -include a space in front and no spaces after.
  • If in a space-separated list, you can enclose unary negative operations in parentheses, such as in 10px (-$var).

- The different meanings of the precedence are as follows:

  1. -As part of the identifier. This means a-1an unquoted string whose value is "a-1". The only exception is units; Sass generally allows any valid identifier to be used as an identifier, but identifiers cannot begin with a number or a hyphen. This means that 5px-3pxand 5px - 3pxare the same.

  2. -Between two numbers without spaces. This indicates subtraction, so 1-2and 1 - 2are the same.

  3. Literal numbers to -begin with. This indicates a negative number, it 1 -2is a contained 1and -2the list (list).

  4. -Between two numbers, with or without spaces. This indicates a subtraction, so 1 -$varand 1 - $varare the same.

  5. -Before the value. This indicates a unary negative operator; the operation requires a number and returns its negative value.

Color operations

All arithmetic operations support color values. The calculation of color values ​​is calculated in segments, that is, the component values ​​of red, green, and blue are calculated in order. E.g:

p {
    color: #010203 + #040506;
  }
  

Computing 01 + 04 = 05, 02 + 05 = 07and 03 + 06 = 09is compiled as follows:

p {
    color: #050709; }
  

Color functions are often more useful than trying color arithmetic to achieve the same effect.

Arithmetic operations between numbers and color values ​​are also segmented. E.g:

p {
    color: #010203 * 2;
  }
  

Computing 01 * 2 = 02, 02 * 2 = 04and 03 * 2 = 06is compiled as follows:

p {
    color: #020406; }
  

Note that colors containing alpha channels (those created by rgba or hsla functions) must have the same alpha value in order to perform color calculations. This arithmetic does not affect the alpha value. E.g:

p {
    color: rgba(255, 0, 0, 0.75) + rgba(0, 255, 0, 0.75);
  }
  

Compiles to:

p {
    color: rgba(255, 255, 0, 0.75); }
  

The alpha channel of the color can be adjusted using the opacify and transparentize functions. E.g:

$translucent-red: rgba(255, 0, 0, 0.5);
      p {
        color: opacify($translucent-red, 0.3);
        background-color: transparentize($translucent-red, 0.25);
  }
  

Compiles to:

p {
    color: rgba(255, 0, 0, 0.8);
    background-color: rgba(255, 0, 0, 0.25); }
  

The IE browser's filters require that all colors include an alpha layer, and the format must be fixed #AABBCCDD. Use the ie_hex_str function to easily convert colors to the format required by IE filters. E.g:

$translucent-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)}');
  }
  

Compiles to:

div {
    filter: progid:DXImageTransform.Microsoft.gradient(enabled='false', startColorstr=#FF00FF00, endColorstr=#80FF0000);
  }
  

String operations

+ Operations can be used to concatenate strings:

p {
    cursor: e + -resize;
  }
  

Compiles to:

p {
    cursor: e-resize; }
  

Please note that if the string is added to the quoted string without quotation marks in (that is, a quoted string in +the left side),
then the results returned is a quoted string. Similarly, if one does not add quoted string to the quoted string (string without quotation marks in +the left) the result returned is not a quoted string belt. E.g:

p:before {
    content: "Foo " + Bar;
    font-family: sans- + "serif";
  }
  

Compiles to:

p:before {
    content: "Foo Bar";
    font-family: sans-serif; }
  

By default, when expressions are used in conjunction with other values, spaces are used as connectors:

p {
    margin: 3px + 4px auto;
  }
  

Compiles to:

p {
    margin: 7px auto; }
  

In text strings, # {}-style interpolation can be used to place dynamic values ​​in strings:

p:before {
    content: "I ate #{5 + 10} pies!";
  }
  

Compiles to:

p:before {
    content: "I ate 15 pies!"; }
  

Null values ​​are treated as empty strings during string interpolation:

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

Compiles to:

p:before {
    content: "I ate  pies!"; }
  

Boolean operations

SassScript support Boolean values and, orand notoperations.

List operations

Arrays do not support any special operations and can only be controlled using the list function .

Parentheses

Parentheses can be used to influence the order of operations (note: priority):

p {
    width: 1em + (2em * 3);
  }
  

Compiles to:

p {
    width: 7em; }
  

Functions

SassScript defines some useful functions that can be called like normal CSS function syntax:

p {
    color: hsl(0, 100%, 50%);
  }
  

Compiles to:

p {
    color: #ff0000; }
  

For a complete list of available functions, see this page .

Keyword Arguments

The Sass function allows calls to be specified with explicit keyword arguments. The above example can also be rewritten as:

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

Although not concise, it can make Sass code easier to read. Keyword parameters make the function have a more flexible interface, even if there are many parameters, it will not make it difficult to use.

Named arguments can be passed in any order, and parameters with default values ​​can be omitted. Because named parameters are also variable names, underscores and dashes can be used interchangeably.

For a complete list of Sass functions and their parameter names, and how to define your own functions in Ruby, see Sass :: Script :: Functions .

Interpolation: #{}(the #{}Interpolation: )

You can also #{}use SassScript variable and attribute names in selectors interpolation syntax:

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

Compiles to:

p.foo {
    border-color: blue; }
  

It can also #{}insert SassScript into attribute values using interpolation statements. In most cases, this may not be as easy to make direct use of variables, but using #{}means near its operators will be treated as plain CSS (Note: to avoid all kinds of operations). E.g:

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

Compiles to:

p {
    font: 12px/30px; }
  

SassScript &( &in SassScript)

Just like when it is used in a selector , SassScript &points to the current parent selector. Below is a comma-separated list with a space-separated list. E.g:

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

$selectorThe value is now ((".foo.bar" ".baz.bang"), ".bip.qux"). This hybrid selector is quoted here to indicate that they are strings, but in reality they will be unquoted. Even if the selector does not contain commas or spaces, &there will always be two levels of nesting, so it guarantees access consistency.

If there is no parent selector, &the value will be empty. This means you can use it in a mixin to detect if the parent selection exists:

@mixin does-parent-exist {
    @if & {
      &:hover {
        color: red;
      }
    } @else {
      a {
        color: red;
      }
    }
  }
  

Variable Default: !default(Variable !defaultDefaults: )

If the value assigned to a variable is followed by a !defaultflag, this means that if the variable has already been assigned, it will not be reassigned, but if it has not already been assigned, then it will be assigned a new given value.

E.g:

$content: "First content";
      $content: "Second content?" !default;
  $new_content: "First time reference" !default;
  
  #main {
    content: $content;
        new-content: $new_content;
  }
  

Compiles to:

#main {
    content: "First content";
    new-content: "First time reference"; }
  

! By default, when assigned, if the variable is nullvalue, it will be treated as unassigned (Note: The value of $ content so the following "Non-null content"):

$content: null;
      $content: "Non-null content" !default;
  
  #main {
    content: $content;
  }
  

Compiles to:

#main {
    content: "Non-null content"; }
  

@Rules @and Directives

Sass CSS3 support all the @rules, and some other specific Sass known "instruction." These Sass has a corresponding effect, for more information, please see the control command (control directives) and mixing instructions (mixin directives) .

@import

Sass extends CSS @importrules to allow it to import SCSS or Sass files. All imported SCSS or Sass files will be merged together into the same CSS file. In addition, any variables or mixins defined in the imported file can be included in the main file (Note: The value of the main file is the file that imports other files, that is, the B file is imported into the A file. Is the A file).

Sass will look for other Sass files in the current directory and the Rack, Rails, Merb directories. Additional search directories can be specified using :load_pathsoptions or options on the command line --load-path.

Normally, @import looks for Sass files and imports them, but in the following cases @import is just a normal CSS statement and does not import any Sass files.

@importNeed a file name to import. By default, it looks for a Sass file to import directly, but in the following cases, it is only used as a regular CSS @import rule statement, and no Sass file is imported.

  • If the file extension is .css.
  • If the file name to http://begin.
  • If the file name is url().
  • If @importit contains any media queries.

If none of the above conditions are met and the extension is .scssor .sass, then the Sass or SCSS file will be imported. If no extension is specified, Sass will try to find the file with the .scssor .sassextension and import it.

E.g,

@import "foo.scss";
  

or

@import "foo";
  

Both lines of code can import the file foo.scss, and

@import "foo.css";
  @import "foo" screen;
  @import "http://foo.com/bar";
  @import url(foo);
  

Compile all to

@import "foo.css";
  @import "foo" screen;
  @import "http://foo.com/bar";
  @import url(foo);
  

Sass in a support @importimport multiple files at the same time rules. E.g:

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

Both files rounded-cornersand are imported text-shadow.

Import rules may contain #{}interpolation, but there are certain restrictions. Sass files cannot be dynamically imported through variables; #{}interpolation is only applicable to CSS import rules. Therefore, it applies only to url()imports.

E.g:

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

Will compile to

@import url("http://fonts.googleapis.com/css?family=Droid+Sans");
  

Partials

If you have an SCSS or Sass file to import but don't want to compile it to a CSS file, you can add an underscore at the beginning of the file name. This will tell Sass not to compile it to a normal CSS file. However, there is no need to add an underscore in the import statement.

For example, you might have a name for the _colors.scssfile, but will not be compiled into a _colors.cssdocument. You can do

@import "colors";
  

In this way, it _colors.scsswill be imported.

Note Do not underlined and not underlined the same file is placed in the same directory, for example, _colors.scssand colors.scsscan not exist simultaneously in the same directory. Otherwise, underlined files will be ignored.

Nesting @import(Nested @import)

Although in most cases it is generally used at the top level of the document (note: the outermost level, not inside nested rules) @import, you can also @mediainclude @importstatements in CSS rules and rules . Like a grassroots @import, where it will contain @importthe contents of the imported file. However, this rule can only be introduced to prevent nesting in the original @importplace.

For example, if example.scsscomprising

.example {
    color: red;
  }
  

Then (Note: introducing into #mainthe style)

#main {
    @import "example";
  }
  

Note: This import is equivalent to:

#main {
    .example {
        color: red;
      }
  }
  

Will be compiled as

#main .example {
    color: red;
  }
  

This directive is only allowed at the top level of the document (Note: the outermost level, not in the nesting rules), like @mixinor @charsetin the file, it is not allowed to be @importimported into a nesting context.

Nesting in mixins or control directives is not allowed @import.

@media

Sass in @mediabehavioral instructions and pure CSS in the same, but added a bit of extra features: they can be nested CSS rules. If a @mediadirective appears in a CSS rule, it will be bubbled to the top of the style sheet and contains all the selectors in the rule. This makes it easy to add specific media styles without having to reuse selectors or disrupt the style sheet writing flow. E.g:

.sidebar {
    width: 300px;
    @media screen and (orientation: landscape) {
      width: 500px;
    }
  }
  

Compiles to:

.sidebar {
    width: 300px; }
    @media screen and (orientation: landscape) {
      .sidebar {
        width: 500px; } }
  

@mediaQueries can also be nested within each other. These queries (queries) at compile time, will use the andoperating symbol combination. E.g:

@media screen {
    .sidebar {
      @media (orientation: landscape) {
        width: 500px;
      }
    }
  }
  

Compiles to:

@media screen and (orientation: landscape) {
    .sidebar {
      width: 500px; } }
  

@media can even use SassScript (such as variables, functions, and operators) instead of condition names or values:

Finally, @mediaqueries can include SassScript expressions (including variables, functions, and operators) instead of feature names and feature values.

$media: screen;
      $feature: -webkit-min-device-pixel-ratio;
  $value: 1.5;
  
  @media #{$media} and ($feature: $value) {
    .sidebar {
      width: 500px;
    }
  }
  

Compiles to:

@media screen and (-webkit-min-device-pixel-ratio: 1.5) {
    .sidebar {
      width: 500px; } }
  

@extend

This is often the case when designing a page: when a style class contains all the styles of another class, and its own specific style. The most common way to deal with this is to use both a generic style class and a special style class in HTML. For example, suppose we design a style that requires both a common error and a severe error. We can write something like this:

<div class="error seriousError">
    Oh no! You've been hacked!
  </div>
  

Our style is as follows

.error {
    border: 1px #f00;
    background-color: #fdd;
  }
  .seriousError {
    border-width: 3px;
  }
  

Unfortunately, this means that we must always remember to use .seriousErrorthem together .error.
This is a burden for maintenance and even leads to tricky mistakes and leads to unspoken styles.

@extendThe directive avoids these problems and tells Sass that the style of one selector should inherit another. E.g:

.error {
    border: 1px #f00;
    background-color: #fdd;
  }
  .seriousError {
    @extend .error;
    border-width: 3px;
  }
  

Compiles to:

.error, .seriousError {
    border: 1px #f00;
    background-color: #fdd;
  }
  
  .seriousError {
    border-width: 3px;
  }
  

This means .errorthat all styles defined also apply .seriousError, except .seriousErrorfor specific styles. Equivalently, every .seriousErrorelement with a .errorclass also carries a class.

Other .errorrules that use the same will be inherited to .seriousError, for example, if we have a special wrong style hack:

.error.intrusion {
    background-image: url("/image/hacked.png");
  }
  

And <div class="seriousError intrusion">we will also use the hacked.pngbackground.

How it works

@extend.errorInsert an extended selector (for example .seriousError) by appearing in the style sheet where the extended selector (for example ) appears . Take the example above:

.error {
    border: 1px #f00;
    background-color: #fdd;
  }
  .error.intrusion {
    background-image: url("/image/hacked.png");
  }
  .seriousError {
    @extend .error;
    border-width: 3px;
  }
  

Compiles to:

.error, .seriousError {
    border: 1px #f00;
    background-color: #fdd; }
  
  .error.intrusion, .seriousError.intrusion {
    background-image: url("/image/hacked.png"); }
  
  .seriousError {
    border-width: 3px; }
  

When merging selectors, she @extendis clever to avoid unnecessary duplication, so like .seriousError.seriousErrorwill convert to .seriousError, and in addition, she won't generate selectors that cannot match any element (for example #main#footer).

Extended Complex Selectors

Class selectors are not the only ones that can be extended. Sass allows any selector defined to a single element to be extended, such as .special.cool, a: hover or a.user [href ^ = "http: //"] Etc, for example:

Class selection is not the only extensibility. She can extend any individual definition of the selector element, such as .special.cool, a:hover, or a.user[href^="http://"]. E.g:

.hoverlink {
    @extend a:hover;
  }
  

As with the class element, this means that the a:hoverdefined styles also apply .hoverlink. E.g:

.hoverlink {
    @extend a:hover;
  }
  a:hover {
    text-decoration: underline;
  }
  

Compiles to:

a:hover, .hoverlink {
    text-decoration: underline; }
  

And the above .error.intrusionexamples, like a:hoverin all styles will to inherit .hoverlink, even including the use of her other styles, such as:

.hoverlink {
    @extend a:hover;
  }
  .comment a.user:hover {
    font-weight: bold;
  }
  

Compiles to:

.comment a.user:hover, .comment .user.hoverlink {
    font-weight: bold; }
  

Multiple Extends

The same selector can expand multiple selectors. This means that it inherits all the styles of the extended selector. E.g:

.error {
    border: 1px #f00;
    background-color: #fdd;
  }
  .attention {
    font-size: 3em;
    background-color: #ff0;
  }
  .seriousError {
    @extend .error;
    @extend .attention;
    border-width: 3px;
  }
  

Compiles to:

.error, .seriousError {
    border: 1px #f00;
    background-color: #fdd; }
  
  .attention, .seriousError {
    font-size: 3em;
    background-color: #ff0; }
  
  .seriousError {
    border-width: 3px; }
  

Each .seriousErrorelement with a class also has .errorclasses and .attentionclasses.
Therefore, the definition of style in the back of the document takes precedence over the definition of style in front of the document: .seriousErrorThe background color is #ff0, rather #fdd, because .attentionin .errorthe definition of the back.

Multiple extensions can also be written with a comma-separated list of selectors. For example, @extend .error, .attentionequivalent @extend .error; @extend .attention.

Chaining Extends

One selector can expand another selector, and another selector expands the third selector selection. E.g:

.error {
    border: 1px #f00;
    background-color: #fdd;
  }
  .seriousError {
    @extend .error;
    border-width: 3px;
  }
  .criticalError {
    @extend .seriousError;
    position: fixed;
    top: 10%;
    bottom: 10%;
    left: 10%;
    right: 10%;
  }
  

Now, with .seriousErroreach element of class will contain .errorclass, with .criticalErroreach element of the class includes not only the .criticalErrorclass will also include .errorclasses, the above code is compiled as follows:

.error, .seriousError, .criticalError {
    border: 1px #f00;
    background-color: #fdd; }
  
  .seriousError, .criticalError {
    border-width: 3px; }
  
  .criticalError {
    position: fixed;
    top: 10%;
    bottom: 10%;
    left: 10%;
    right: 10%; }
  

Selector Sequences

Selector sequences such as .foo .baror .foo + .barare not currently available as extensions. However, the selector sequence itself can be used @extend. E.g:

#fake-links .link {
    @extend a;
  }
  
  a {
    color: blue;
    &:hover {
      text-decoration: underline;
    }
  }
  

Will be compiled to:

a, #fake-links .link {
    color: blue; }
    a:hover, #fake-links .link:hover {
      text-decoration: underline; }
  
Merging Selector Sequences

Sometimes a selector sequence extends another selector, and this selector appears in another selector sequence. In this case, the two selector sequences need to be merged. E.g:

#admin .tabbar a {
    font-weight: bold;
  }
  #demo .overview .fakelink {
    @extend a;
  }
  

Technically speaking, it can generate the results of all the matching conditions, but the style sheet generated is too complicated. The simple example above may have 10 results. So, Sass will only compile and output useful selectors.

When two columns are merged, if they do not contain the same selector, two new selectors are generated: the first is listed before the second, or the second is listed before the first. E.g:

#admin .tabbar a {
    font-weight: bold;
  }
  #demo .overview .fakelink {
    @extend a;
  }
  

Compiles to:

#admin .tabbar a,
  #admin .tabbar #demo .overview .fakelink,
  #demo .overview #admin .tabbar .fakelink {
    font-weight: bold; }
  

If two columns contain the same selector, the same parts will be merged together, and the other parts will be output alternately. In the following example, both columns are included #admin, and they are merged together in the output:

#admin .tabbar a {
    font-weight: bold;
  }
  #admin .overview .fakelink {
    @extend a;
  }
  

Compiles to:

#admin .tabbar a,
  #admin .tabbar .overview .fakelink,
  #admin .overview .tabbar .fakelink {
    font-weight: bold; }
  

@extend-Only @extendSelectors

Sometimes you just want to write a @extendextended style class, you do not want to use directly in your HTML. When writing a Sass style library, which is particularly useful if they need to, where you can provide @extendextended style to the user, if they do not directly overlooked.

In this case, if you use ordinary style classes, you will have a lot of extra (note: useless) CSS in the style sheet you end up generating, and it is easy to cause when HTML is used in combination with other style classes. conflict. That's why Sass supports "placeholders" (for example, %foo).

Placeholder selector looks like an ordinary class and id selector only #, or .is replaced %. It can be used like a class or id selector, and its rules are not compiled into CSS files. E.g:

// This ruleset won't be rendered on its own.
  #context a%extreme {
    color: blue;
    font-weight: bold;
    font-size: 2em;
  }
  

Placeholder selectors, just like class and id selectors, can be used for extensions. Extension selectors will be compiled into CSS, and placeholder selectors themselves will not be compiled. E.g:

.notice {
    @extend %extreme;
  }
  

Compiles to:

#context a.notice {
    color: blue;
    font-weight: bold;
    font-size: 2em; }
  

!optionalThe !optionalFlag

Usually, when you expand a selector, if it @extenddoesn't work, you will get an error message.
For example, if there is no .noticeselector, so you write a.important {@extend .notice}, it will be thrown. If only h1.noticeone selector is included .notice, an error will also be reported. As h1will the aconflict, and will not generate a new selector.

However, sometimes, you @extenddon't want to generate any new selectors. Just after selecting add !optionallogo on it. E.g:

a.important {
    @extend .notice !optional;
  }
  

Instruction @extend( @extendin Directives)

In the instruction @extendtime (such as in the @mediamiddle), there are some limitations: Sass will not @mediaexpand the outer layer to CSS rules CSS layer in the instruction, it will generate a lot of dead code. This means that if used in @media(or other CSS directives) @extend, it must be extended to selectors in the same directive layer.

The following example works:

@media print {
    .error {
      border: 1px #f00;
      background-color: #fdd;
    }
    .seriousError {
      @extend .error;
      border-width: 3px;
    }
  }
  

But the following example will report an error:

.error {
    border: 1px #f00;
    background-color: #fdd;
  }
  
  @media print {
    .seriousError {
      // INVALID EXTEND: .error is used outside of the "@media print" directive
      @extend .error;
      border-width: 3px;
    }
  }
  

I hope that one day, the browser can natively supports @extendinstruction, so that you can @mediause and extend the functionality of other instructions.

@at-root

@at-rootDirectives cause one or more rules to be restricted to output at the root level of the document, rather than being nested under its parent selector.
It can be used with single or inline selectors:

.parent {
    ...
    @at-root .child { ... }
  }
  

This will generate:

.parent { ... }
  .child { ... }
  

Or it can be used in a code block containing multiple selectors:

.parent {
    ...
    @at-root {
      .child1 { ... }
      .child2 { ... }
    }
    .step-child { ... }
  }
  

This will output the following:

.parent { ... }
  .child1 { ... }
  .child2 { ... }
  .parent .step-child { ... }
  

@at-root (without: ...)And @at-root (with: ...)( @at-root (without: ...)and `@ at-root (with: ...))

By default, @at-rootselectors are simply excluded. However, it can also be used to @at-rootmove selectors out of nested instructions (for example @media). E.g:

@media print {
    .page {
      width: 8in;
      @at-root (without: media) {
        color: red;
      }
    }
  }
  

generate:

@media print {
    .page {
      width: 8in;
    }
  }
  .page {
    color: red;
  }
  

You can use to @at-root (without: ...)move rules out of any instruction. You can also make multiple instructions to do this, as long as a plurality of instructions can be separated by spaces: the @at-root (without: media supports)will to move rules @mediaand @supportsqueries (queries) away.

There are two special values ​​you can pass to @at-root. "rule" refers to normal CSS rules; @at-root (without: rule)equivalent to no query @at-root. @at-root (without: all)This means that the style should move beyond all directives and CSS rules.

If you want to specify which directives or rules are included, rather than which should be excluded, then you can use withinstead without.
For example, @at-root (with: rule)move the rule out of all directives, but keep it inside the CSS rules.

@debug

@debugThe instruction prints the value of a SassScript expression to the standard error output stream. This is useful for debugging Sass files with complex SassScript expressions. E.g:

@debug 10em + 12em;
  

Output:

Line 1 DEBUG: 22em
  

@warn

@warnThe instruction prints the value of a SassScript expression to the standard error output stream. This is useful to warn users to deprecate libraries or fix minor errors in mixins. @warnAnd @debugthere are major differences between the two:

  1. You can turn off warnings using --quietcommand line options or :quietSass options.
  2. Style sheet tracking will be printed with the message so that users can see where their style caused the warning.

Example usage:

@mixin adjust-location($x, $y) {
    @if unitless($x) {
          @warn "Assuming #{$x} to be in pixels";
          $x: 1px * $x;
        }
        @if unitless($y) {
      @warn "Assuming #{$y} to be in pixels";
          $y: 1px * $y;
        }
        position: relative; left: $x; top: $y;
  }
  

@error

@errorThe instruction throws the value of a SassScript expression as a fatal error, which includes a nice stack trace. This is useful for verifying mixins and function parameters. E.g:

@mixin adjust-location($x, $y) {
    @if unitless($x) {
          @error "$x may not be unitless, was #{$x}.";
        }
        @if unitless($y) {
      @error "$y may not be unitless, was #{$y}.";
        }
        position: relative; left: $x; top: $y;
  }
  

There is currently no way to catch errors.

Control Directives & Expressions

SassScript supports some basic control instructions and expressions, such as including styles only under certain conditions, or including the same style several times.

Note: The control instruction is an advanced feature that is not commonly used in daily writing. It is mainly used in mixins instructions, especially libraries like Compass .

if()

Built-in if()functions let you process branches in one condition and return two possible results. It can be used in any script context. ifThe function evaluates only the corresponding parameter and returns-this allows you to reference a variable that has been defined or can be calculated, otherwise it will cause an error (for example, division by zero).

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

@if

@ifInstruction requires a SassScript expression and the nested style below it to be used, if the expression value is not returned falseor null, then spend behind in brackets will return:

p {
    @if 1 + 1 == 2 { border: 1px solid;  }
    @if 5 < 3      { border: 2px dotted; }
    @if null       { border: 3px double; }
  }
  

Compiles to:

p {
    border: 1px solid; }
  

@ifBehind the statement with multiple @else ifstatements and a @elsestatement.
 If the @ifstatement fails, Sass will try the @else ifstatements one by one until one succeeds, or if all fails, the @elsestatement will be executed . E.g:

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

Compiles to:

p {
    color: green; }
  

@for

@forThe instruction repeatedly outputs a set of styles. For each iteration, the counter variable is used to adjust the output. This instruction has two forms: @for $var from <start> through <end>and @for $var from <start> to <end>. Note the keywords throughand todifferent. $varIt can be any variable name, for example $i; <start>and <end>should return an integer SassScript expression. When the <start>ratio is <end>larger, the counter is decremented instead of incremented.

@forThe statement is set $varto each consecutive value in the specified range, and $varthe value used in the nested style of each output . For from ... througha form, the range including<start> and <end>values, but from ... tothe form of the <start>operation start, but does not include<end> value. Using throughsyntax,

@for $i from 1 through 3 {
        .item-#{$i} { width: 2em * $i; }
  }
  

Compiles to:

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

@each

@eachThe format of the instruction is usually @each $var in <list or map>. $varIt can be any variable name, like $lengthor $name, and <list or map>is a SassScript expression that returns a list or map.

@eachThe rule will be $varset to each item in the list or map, with $varthe values used in the output style . E.g:

@each $animal in puma, sea-slug, egret, salamander {
        .#{$animal}-icon {
          background-image: url('/images/#{$animal}.png');
    }
  }
  

Compiles to:

.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 Assignment

@eachInstructions can also use multiple variables in the format @each $var1,$var2, ... in <list>. In the case <list>of a list, each element in the sublist is assigned to its own variable. E.g:

@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;
    }
  }
  

Compiles to:

.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; }
  

Because maps are treated as a list of key-value pairs, multiple assignments also work well. E.g:

@each $header, $size in (h1: 2em, h2: 1.5em, h3: 1.2em) {
    #{$header} {
          font-size: $size;
    }
  }
  

Compiles to:

h1 {
    font-size: 2em; }
  h2 {
    font-size: 1.5em; }
  h3 {
    font-size: 1.2em; }
  

@while

@whileThe instruction repeatedly outputs the nested style until the SassScript expression returns a result false. This can be used to implement @formore complex loops than statements, but it is rarely used such as:

$i: 6;
      @while $i > 0 {
    .item-#{$i} { width: 2em * $i; }
        $i: $i - 2;
  }
  

Compiles to:

.item-6 {
    width: 12em; }
  
  .item-4 {
    width: 8em; }
  
  .item-2 {
    width: 4em; }
  

Mixin Directives

Mixins allow you to define styles that can be reused throughout the stylesheet without the use of non-semantic classes, such as .float-left. Mixins can also include all CSS rules, and anything else allowed in Sass documents.
They can even bring arguments , introduce variables, and output a variety of styles with a small amount of mixin code.

Definition of a mixed (a mixin): @mixin(A Mixin the Defining: @mixin)

Mixing (a mixin) by the @mixindefinition instruction. It is followed by the name of the mixin and optional arguments (parameters) , and the content block of the mixin. For example, large-textmixin is defined as follows:

@mixin large-text {
    font: {
      family: Arial;
      size: 20px;
      weight: bold;
    }
    color: #ff0000;
  }
  

Blends can also contain a mix of selectors and attributes, and selectors can even contain parent references . E.g:

@mixin clearfix {
    display: inline-block;
    &:after {
      content: ".";
      display: block;
      height: 0;
      clear: both;
      visibility: hidden;
    }
    * html & { height: 1px }
  }
  

For historical reasons, mixin names (and all other Sass identifiers) are interchangeable with hyphens and underscores. For example, if you define a add-columnmixin named , you can treat it as a add_columnvice-versa.

Reference style mixing: @include(A Mixin Including: @include)

Use @includeinstructions may be mixed into (a mixin) introduced into the document. This requires a mixin name and optional parameters to be passed to it , and includes the style of the current rule defined by the mixin. E.g:

.page-title {
    @include large-text;
    padding: 4px;
    margin-top: 10px;
  }
  

Compiles to:

.page-title {
    font-family: Arial;
    font-size: 20px;
    font-weight: bold;
    color: #ff0000;
    padding: 4px;
    margin-top: 10px; }
  

Mixins can also be included outside of any rule (ie, at the root of the document), as long as they don't directly define any attributes or use any parent selector references. E.g:

@mixin silly-links {
    a {
      color: blue;
      background-color: red;
    }
  }
  
  @include silly-links;
  

Compiles to:

a {
    color: blue;
    background-color: red; }
  

A mixin definition can also include other mixins. E.g:

@mixin compound {
    @include highlighted-background;
    @include header-text;
  }
  
  @mixin highlighted-background { background-color: #fc0; }
  @mixin header-text { font-size: 20px; }
  

Mixing can include itself. This behavior is different from versions before Sass 3.3, where mixin recursion was previously prohibited.

A mix-in that only defines descendant selectors can be safely mixed into the top level of the file.

Arguments

Mixins can take SassScript values ​​as parameters. The given parameters are included in the mixin and provided to the mixin as variables.

When defining a mixin, the parameter is used as the variable name and written in parentheses after the mixin name. Multiple parameters can be separated by commas. Then, when the mixin is called, the values ​​are passed in the corresponding parameter order. E.g:

@mixin sexy-border($color, $width) {
    border: {
      color: $color;
          width: $width;
      style: dashed;
    }
  }
  
  p { @include sexy-border(blue, 1in); }
  

Compiles to:

p {
    border-color: blue;
    border-width: 1in;
    border-style: dashed; }
  

Mixins can also specify default values ​​for parameters using ordinary variable assignment syntax. Then, when calling mixin, if no parameter is assigned a value, the default value is automatically used instead. E.g:

@mixin sexy-border($color, $width: 1in) {
    border: {
      color: $color;
          width: $width;
      style: dashed;
    }
  }
  p { @include sexy-border(blue); }
  h1 { @include sexy-border(blue, 2in); }
  

Compiles to:

p {
    border-color: blue;
    border-width: 1in;
    border-style: dashed; }
  
  h1 {
    border-color: blue;
    border-width: 2in;
    border-style: dashed; }
  

Keyword Arguments

Mixins @includecan also use explicit keyword arguments when they are introduced ( instructions). For example, the above example can be written as:

p { @include sexy-border($color: blue); }
      h1 { @include sexy-border($color: blue, $width: 2in); }
  

Although this is not concise enough, it can make the style sheet easier to read. It presents a more flexible interface to functions, which makes multi-parameter mixing easier to call.

Named parameters can be passed in any order, and parameters with default values ​​can be omitted. Because named parameters are variable names, underscores and hyphens can be used interchangeably.

Variable Arguments

Sometimes it is not possible to determine how many parameters a mixin or function uses. For example, a mixin used to create a box-shadow can take any number of box-shadows as parameters. For these cases, Sass supports "variable parameters" where parameters are declared at the end of a mixin or function and all remaining parameters are packed into a list . Parameters look just like ordinary parameters, but are followed by them .... E.g:

@mixin box-shadow($shadows...) {
        -moz-box-shadow: $shadows;
        -webkit-box-shadow: $shadows;
        box-shadow: $shadows;
  }
  
  .shadows {
    @include box-shadow(0px 4px 5px #666, 2px 6px 10px #999);
  }
  

Compiles to:

.shadows {
    -moz-box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
    -webkit-box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
    box-shadow: 0px 4px 5px #666, 2px 6px 10px #999;
  }
  

Variadic parameters can contain any keyword arguments passed to a mixin or function. These can be accessed using keywords($args)functions , returning a map, parameter name strings (none $), and value key-value pairs.

Variadic parameters can also be used when calling (@include directives) a mixin. Using the same syntax, you can expand a list of values ​​so that each value is passed in as a separate parameter, or a map of values ​​to make each key-value pair treated as a keyword parameter. E.g:

@mixin colors($text, $background, $border) {
        color: $text;
        background-color: $background;
        border-color: $border;
  }
  
  $values: #ff0000, #00ff00, #0000ff;
      .primary {
        @include colors($values...);
  }
  
  $value-map: (text: #00ff00, background: #0000ff, border: #ff0000);
      .secondary {
        @include colors($value-map...);
  }
  

Compiles to:

.primary {
    color: #ff0000;
    background-color: #00ff00;
    border-color: #0000ff;
  }
  
  .secondary {
    color: #00ff00;
    background-color: #0000ff;
    border-color: #ff0000;
  }
  

You can pass a list and a map parameter at the same time, as long as the list is before the map, for example @include colors($values..., $map...).

You can use variable parameters to wrap a mixin and add extra styles without changing the parameter signature of the mixin. If you do this, the keyword arguments will be passed directly through the wrapped mixin. E.g:

@mixin wrapped-stylish-mixin($args...) {
        font-weight: bold;
        @include stylish-mixin($args...);
  }
  
  .stylish {
    // The $width argument will get passed on to "stylish-mixin" as a keyword
        @include wrapped-stylish-mixin(#00ff00, $width: 100px);
  }
  

Passing Content Blocks to a Mixin

The style content block can be passed to the mixin where the style is contained. Any style content block will appear in a mixed @contentposition command. This makes it possible to define the parsing of abstract associations to selectors and instructions.

E.g:

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

generate:

* html #logo {
    background-image: url(/logo.gif);
  }
  

The same mixing (a mixin) may be .sassabbreviated syntax ( @mixinmay be =expressed, and @includecan be +represented) is accomplished:

=apply-to-ie6-only
    * html
      @content
  
  +apply-to-ie6-only
    #logo
      background-image: url(/logo.gif)
  

Note: When the @contentinstruction is specified multiple times or in a loop, the style block will be copied and referenced in each call.

Variable Scope and Content Blocks

The content block passed to the mixin is evaluated in its defined scope, not the scope of the mixin. This means that local variables of the mixin cannot be passed to the style block and the variables will be resolved to global values:

$color: white;
      @mixin colors($color: blue) {
    background-color: $color;
        @content;
        border-color: $color;
  }
  .colors {
    @include colors { color: $color; }
  }
  

Compiles to:

.colors {
    background-color: blue;
    color: white;
    border-color: blue;
  }
  

Also, this clearly shows that variables and mixins passed into the block point to other styles around the block definition. E.g:

#sidebar {
    $sidebar-width: 300px;
        width: $sidebar-width;
    @include smartphone {
      width: $sidebar-width / 3;
    }
  }
  

Function Directives

Sass supports custom functions and can be used in any value or script context. E.g

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

Becomes:

#sidebar {
    width: 240px; }
  

As you can see, functions can access any globally defined variables and accept parameters, just like a mixin. Functions can contain statements, and you must call @returnto set the function's return value.

As with mixins, you can use keyword arguments to call Sass-defined functions. In the above example, we can call the function like this:

#sidebar { width: grid-width($n: 5); }
  

It is recommended that you prefix the functions to avoid naming conflicts. When others read the stylesheets, they will know that they are not native to Sass or CSS. For example, if you work for ACME, you can name the function above -acme-grid-width.

User-defined functions also support variable parameters in the same way as mixins.

For historical reasons, hyphens and underscores are interchangeable in function names (and all other Sass identifiers). For example, if you define a grid-widthfunction named , you can do it by grid_widthcalling it and vice versa.

Output style

Although Sass's default CSS output format is very good and reflects the structure of the document, because everyone's preferences and needs are different, Sass supports several other formats.

Sass provides four output formats, which can be set via the :styleoptions option, or using the --style option on the command line.

Sass allows you to set :styleoptions or use the --stylecommand line flag to choose between four different output formats.

:nested

The nested format is Sass's default output format because its format reflects CSS styles and HTML document structure. Each attribute occupies a separate line, but indentation is not fixed. Each rule is indented based on its nesting depth. E.g:

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

The nested format is very useful when reading large CSS files: you don't have to read them in detail to make it easy to grasp the structure of the file.

:expanded

The expanded format is more like hand-written CSS styles, with each property and rule on its own line. The attributes within the rule are indented, but the rule does not have any special indentation. E.g:

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

:compact

The compact format takes up less space than the nested or expanded format. This format focuses on selectors, not their attributes. Each CSS rule occupies a separate line, and this line also includes each attribute defined. Nested rules are on a separate line, and non-nested selectors output blank lines as separators. E.g:

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

:compressed

The compressed format occupies as little space as possible, there will be a newline at the end of the file, and there are basically no extra spaces except for the necessary delimiting selector. It also includes some other small compression, such as choosing the smallest color Representation. This means poor readability. E.g:

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

Extending Sass

For unique needs, Sass offers users a number of advanced customization features. Using these features requires a deep understanding of Ruby.

Defining Custom Sass Functions

Users can customize Sass function by Ruby API, for more information please see the source code documentation .

Cache Stores

Sass caches documents that have already been parsed, which makes them reusable without having to parse them again unless they have been changed. By default, Sass these cache files will be written to :cache_locationthe specified file system. If you can't write to the file system or need a ruby ​​process or computer to share the cache, then you can define your own cache storage and set :cache_storeoptions . For more information on creating a custom cache store, check out the source code documentation .

Custom Importers

Sass import is mainly responsible for getting the paths passed to @importand finding the corresponding Sass code for these paths. By default, this code is loaded from the file system , but Importers can be loaded from the database, added to Sass via HTTP, or using a different file naming scheme.

Each importer is responsible for a separate load path (or any corresponding backend concept). The importer can be placed in :load_pathsan array along with a normal file system path .

When parsing one @import, Sass will successfully import the path by looking for the importer by loading the path. Once found, the imported file is used.

User-created imports must inherit from Sass :: Importers :: Base .