SassSass (3.4.21) Chinese document

Sass is a CSS extension that builds on CSS syntax and allows you to use features such as variables, nested rules, mixins, inline imports, etc. Make CSS more powerful and elegant. Using the Sass and Compass style libraries helps to organize style files better and to develop projects more efficiently.

The Features

  • Fully compatible with CSS3
  • Adding features such as variables, nesting, and mixins to the CSS language
  • The color value and attribute value are calculated by the function
  • Provides advanced functions such as control commands
  • Customize the output format

Syntax

There are two syntax formats for Sass. The first is SCSS (Sassy CSS), the format used in this reference example, which only extends the CSS3 syntax, meaning that each CSS stylesheet is an equivalent SCSS file. SCSS also supports most CSS hacks and browser-specific syntax, such as IE's archaic filter syntax. The stylesheet file for this syntax needs to be extended by.scss.

Another, and earliest, syntax is called Indented Sass, or "Sass" as it is commonly called, and it provides a much more concise way to write CSS. It uses indentation instead of curly braces to indicate nested selectors, and newlines instead of semicolons to separate attributes, which some consider easier to read and faster to write than SCSS. Indentation syntax has all the features of Sass, although some syntax is slightly different; The specific differences are described in the indent Syntax reference. Stylesheet files that use this syntax need to have a.sass extension.

Files of either syntax can be directly imported into files of the other syntax, and you can convert one syntax into another just by using the ASS-convert command line tool:

# 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 the sass command described elsewhere.

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're using Windows, you'll probably need to install Ruby first.

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

sass input.scss output.css

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

sass --watch input.scss:output.css

If you have a lot of Sass files in your directory, you can also use the Sass command to monitor the entire directory:

sass --watch app/sass:public/stylesheets

Use sass --help to list the complete help documentation.

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

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, add a line of code in the config/dependencies.rb file:

dependency "merb-haml"

To enable Sass in a Rack application, you need to add the following code in the config.ru file:

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

Sass style sheets work differently than views. It does not contain any dynamic content, so it only needs to generate CSS when the Sass file is updated. By default,.sass and.scss files are placed in the public/stylesheets/sass directory (this can be configured with the :template_location option). Then, when needed, they are compiled into the appropriate CSS file and placed in the public/stylesheets directory. For example, public/stylesheets/sass/main SCSS document will be compiled to public/stylesheets/main CSS file.

Caching

By default, Sass automatically caches compiled templates and partials, which can significantly improve the speed of recompilation, especially when Sass templates are cut into multiple files and imported via @import to form a large file.

If no framework is used, Sass will put the cached template in the.sass-cache directory. In Rails and Merb, cached templates are placed in the tmp/sass-cache directory. This directory can be customized with the :cache_location option. If you do not want Sass to enable caching, you can set the :cache option to false.

Configuration Options

The options can be set to Sass::Plugin#options hash, which is set in the environment.rb file in Rails or config.ru file in Rack:

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

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

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

Or by passing an options hash to Sass::Engine#initialize, all related options are also available in sass and scss command line executables via tags. Available options are:

Options Description
:style Set the output CSS code style, you can viewThe output code style.
:syntax Input file syntax,:sassDenotes the indent syntax,:scssRepresents the CSS extension syntax. Only in your own constructionSass::EngineUseful in case of instance; When you useSass::PluginIt will automatically set the correct value. The default setting is:sass
:property_syntax Force the indent syntax document to use an attribute syntax. If the correct syntax is not used, an error is thrown.:newValue enforces the use of a colon after the attribute name. For example:color: #0f3perhapswidth: $main_width:oldValue to force the use of a colon before the attribute name. For example::color #0f3perhaps:width $main_width. By default, both syntax is valid. This option is useful for SCSS (.scssThe document is invalid.
:cache Whether Sass should be cached when parsed, allowing for faster compilation. The default setting istrue
:read_cache If this option is set, but not set:cacheOption, then the cache is present if read-only Sass cache, if there is no cache, then no compilation.
:cache_store If this option is set toSass::CacheStores::BaseThe cache store will be used to store and retrieve cached compilation results. The default setting isSass::CacheStores::Filesystem, initialize the use:cache_locationOptions.
:never_update CSS files should never be updated, even if the template file changes. Set it totrueMay result in a small performance boost. It always defaults tofalse. This option only makes sense in Rack, Ruby on Rails, or Merb.
:always_update CSS files should always be updated, even when each controller is accessed, not only when templates are modified. By defaultfalse. This option only makes sense in Rack, Ruby on Rails, or Merb.
:always_check Sass templates should always be checked for updates, even when each controller is accessed, not only when the service is started. If a Sass template is updated, it is recompiled and overwritten with the corresponding CSS file. In production mode, the default isfalse, otherwisetrue. This option only makes sense in Rack, Ruby on Rails, or Merb.
:poll iftrue, always useSass::Plugin::Compiler#watchBack-end polling rather than the back-end of the native file system.
:full_exception Whether errors in Sass code should be detailed in the generated CSS file. If set totrueThis error will be displayed in the comments of the CSS file and at the top of the page (supported browsers), including the line number and source code snippet. Otherwise, the exception will be alerted in Ruby code. In production mode, the default isfalse, otherwisetrue.
:template_location A path to apply the Sass template in the root directory. If you hash,:css_locationWill be ignored, and this option specifies the mapping between the input and output directories. You can also give a binary list, instead of a hash. By defaultcss_location + "/sass". This option only makes sense in Rack, Ruby on Rails, or Merb. Note that if you specify more than one template location, they are all placed in the import path, allowing you to import between them.
It is important to note that since it can take many possible formats, this option should only be set directly and should not be accessed or modified. UseSass::Plugin#template_location_arraySass::Plugin#add_template_locationSass::Plugin#remove_template_locationMethods to replace.
:css_location CSS file output path, when:template_locationWhen the option is a hash, this option is ignored. The default setting is"./public/stylesheets". This option only makes sense in Rack, Ruby on Rails, or Merb.
:cache_location Among them, cachesasscThe path to which the file should be written. The default in Rails and Merb is"./tmp/sass-cache"Otherwise, the default is"./.sass-cache". If set:cache_storeOptionsThis will be ignored.
:unix_newlines If true, Unix-style line breaks are used when writing to the file. It only makes sense on Windows, and only when Sass is written to a file (in Rack, Rails, or Merb, used directly)Sass::PluginWhen, or when using a command line executable).
:filename The name of the file to be rendered. This is entirely for reporting errors, set automatically when using Rack, Rails, or Merb.
:line Sass Specifies the line number of the first row of the 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 that contains file systems or passes@importThe path of the Sass template imported by the directive. They could be strings,Pathname(pathname) object or yesSass::Importers::BaseA subclass of. This option defaults to the working directory, and in Rack, Rails, or Merb, this option has a value of:template_location. The load path can also be determined bySass.load_pathsandSASS_PATHEnvironment variable notification.
:filesystem_importer singleSass::Importers::BaseA subclass that handles the load path of ordinary strings. This should import files from the file system. This should be a string argument (load path) inherited from a constructorSass::Importers::BaseClass object. By defaultSass::Importers::Filesystem.
:sourcemap Control how sourcemap is produced. These sourcemaps tell the browser how to find Sass styles and thus generate each CSS style. This option has three valid values::autoUse relative URIs where possible, assuming the source style is provided on whatever server you use, then their relative location 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.:inlineIt is most convenient to include the complete source text in the sourcemap, but it is possible to produce very large sourcemap files. And finally,:noneCauses the sourcemap file to never be generated.
:line_numbers When set totrueThe line number and file name of the defined selector are injected into the compiled CSS as comments. This is useful for debugging, especially using@importand@mixinWhen. This option has an alias:line_comments. When in use:compressedOutput style or use:debug_info/:trace_selectorsThis option is automatically disabled.
:trace_selectors When set totrueWill be injected before each selector@importand@mixinThe full trajectory. The debugging succeeds in the browser@importand@mixinIt is useful to include stylesheets. This option will replace:line_commentsOption and be:debug_infoOption replace. When in use:compressedThis option is automatically disabled when you output a style.
:debug_info When set totrueThe line number and file name of the defined selector are injected into the compiled CSS and can be recognized by the browser. Be used forFireSass Firebug extensionTo display the Sass file name and line number. When in use:compressedThis option is automatically disabled when you output a style.
:custom This option can be used for a single application setting to make the data availableCustomize Sass functions.
:quiet When set totrueWhen the warning message is disabled.

Syntax Selection (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. The sass command line program defaults to indent syntax, but if the input should be parsed to SCSS syntax, you can pass the --scss option to her. In addition, you can use the scss command line program, which is exactly the same as the sass program, but its default syntax is SCSS.

Encoding format (Encodings)

When running Sass in Ruby 1.9 and above, Sass is sensitive to the encoding format of the file, first determining the encoding format of the style file based on CSS spec, and if that fails, detecting the Ruby string encoding. That is, Sass first checks the Unicode byte order markup, then the @charset declaration, and finally the Ruby string encoding, and if neither is detected, the default encoding is UTF-8.

To explicitly specify the encoding of the style sheet, as with CSS, use the @charset declaration. Insert @charset "encod-name" at the start of the style file (without any white space and comments); Sass will compile the file according to the given encoding format. Note that whatever encoding you use, it must be able to convert to the Unicode character set.

By default, Sass always outputs CSS files in UTF-8 encoding. The @charset declaration is added to the output file if and only if the output file contains non-ASCII characters, in compressed mode, where the UTF-8 byte order tag is used instead of the @charset declaration statement.

CSS Extensions (CSS Extensions)

Nested Rules

Sass allows you to nest a CSS style into another style, the inner style only applies to the scope of the outer style selectors (fool's pier note: can understand the hierarchy selector), for example:

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

Compile to:

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

This helps avoid duplicate parent selectors, which is much simpler than multiple nested selectors in complex CSS layouts. For example:

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

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

Referencing Parent Selectors: & (Referencing Parent Selectors: &)

This is useful when you need to use the nested parent selector directly, for example, you might like to specify the hover style for the selector, or when the body element has a style, in which case you can explicitly insert the specified parent selector with the & character. For example:

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

Compile to:

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

& will be replaced by the parent selector rendered in the CSS file. This means that if you have a multi-layer nested rule, the parent selector will be completely decomposed before being replaced by &. For example:

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

Compile to:

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

Ampersand must appear at the beginning of the selector (Fool's Wharf note: that is, as the first character of the selector), but can be followed by a suffix that will be added to the end of the parent selection. For example:

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

Compile to:

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

Sass will throw an error when the parent selector & is used as a suffix.

Nested Properties

Some properties in CSS follow the same "namespace"; For example, font-size, font-size, and font-size are all in the font namespace. In CSS, if you want to set a list of properties in the same namespace, you have to output it every time. Sass provides a shortcut for this: you only need to enter a namespace once, and then nest subattributes inside it. For example:

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

Compile to:

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

Namespaces can also have their own attribute values. For example:

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

Compile to:

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

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

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

Rulesets that use placeholder selectors will not be rendered as CSS when they are used alone, i.e. without @extend.

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

Sass supports standard CSS multi-line comments with /* */ and single-line comments with //. Where possible, multi-line comments are kept in the output CSS, while single-line comments are removed. For example:

/* 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; }

Compile 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! Comments are always retained in the output CSS, even in compressed output mode. This can be used to add a copyright notice to your generated CSS.

With interpolation, you can output a variable value to a multi-line comment, for example:

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

Compile to:

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

SassScript

In addition to the normal CSS attribute syntax, Sass supports several extensions called SassScript. SassScript allows properties to use variables, arithmetic, and additional functionality. SassScript can be used on any property value.

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

Interactive shell (Interactive Shell)

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

You can easily try SassScript using an Interactive Shell. To run the box startup shell, just use the sass command line with the -i option (Fool Dock note: type sass -i on the command line). At the prompt, enter any valid SassScript expression, which evaluates and prints out your results:

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

Variables:$(Variables:$

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

$width: 5em;

You can refer to them in properties:

#main {
  width: $width;
}

A variable is only available within the scope of the selector nesting level it defines (block-level scope). Variables not defined in any nested selector can be used anywhere (fool's Wharf note: can be understood as global variables). You can bring it back when you define variables! global flag, in which case the variable is visible anywhere (Fool's Wharf note: can be understood as a global variable). For example:

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

Compile to:

#main {
  width: 5em;
}

#sidebar {
  width: 5em;
}

For historical reasons, variable names (and all other Sass identifiers) are interchangeable with hyphens (Fool's Wharf note: -) and underscores (Fool's Wharf note: _). For example, if you define an object named $main-width, you can access it using $main_width, and vice versa.

Data Types (Data Types)

SassScript supports 7 main data types:

  • Numbers (e.g.1.2, 13, 10px)
  • Text strings, quoted strings and unquoted strings (e.g."foo", 'bar', baz)
  • Color (e.g.blue, #04a3f9, rgba(255, 0, 0, 0.5))
  • Boolean values (e.g.true, false)
  • Null values (e.g.null)
  • list of values, separated by Spaces or commas (e.g.1.5em 1em 0 2em, Helvetica, Arial, sans-serif)
  • maps, mapping from one value to another (e.g.(key1: value1, key2: value2))

SassScript also supports all other types of CSS property values, such as Unicode character sets, or! An important statement. However, these types of property values are not treated in a special way and are treated as unquoted strings.

Strings

CSS specifies two types of strings: quoted strings, such as "Lucida Grande" or "http://sass-lang.com", and unquoted strings, such as sans-serif or bold. SassScript recognizes both types and, in general, does not change the string types used in Sass documents in the compiled output CSS file.

One exception is that when #{} interpolation is used, quoted strings are compiled to unquoted strings, mainly for ease of use, such as selector names in mixins. For example:

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

Compile to:

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

Lists (Lists)

lists refer to how Sass is represented in the CSS declaration, like margin: 10px 15px 0 0 or font-face: With values like Helvetica, Arial, sans-serif, a list is just a string of other values, whether separated by Spaces or commas. In fact, independent values are also considered lists: lists that contain only one value.

Lists don't do much on their own, but the Sass list functions give arrays more functionality: the nth function can access an item directly in an array; The join function can join multiple arrays together; The append function adds new values to the array; The @each instruction is capable of traversing every item in the group.

Lists don't have much functionality on their own, but the SassScript list functions make them very useful. The nth function can directly access an item in the list; The join function can concatenate multiple lists together; The append function adds an item to the list; The @each directive can add styles to each item in the list.

In addition to containing simple values, a list can contain other lists. For example, 1px 2px, 5px 6px contains a 1px 2px list and a 5px 6px list. If the inner and outer lists use the same separator, you need to enclose the inner list with parentheses to clarify where the inner category starts and ends. For example, (1px 2px) (5px 6px) is also a list with two items: a 1px 2px list and a 5px 6px list. The difference is that the outer layer of the column is separated by a space, whereas the outer layer of the previous list was separated by a comma.

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

Use () to represent an empty array that does not contain any values (also considered an empty map after Sass version 3.3). Empty arrays cannot be compiled directly into CSS. For example, compiling font-family: () Sass will result in an error. If the array contains an empty array or null value, it will be cleared at compile time, such as 1px 2px () 3px or 1px 2px null 3px.

A list can also have no items. These lists can be represented by () (also an empty map). They cannot output directly to CSS; If you try to do this, for example, font-family: (), Sass will report an error. If the list contains an empty list or a null value, such as 1px 2px () 3px or 1px 2px null 3px, the empty list and null value will be deleted before the list is compiled into CSS.

Comma-separated lists can retain the ending comma. This is especially useful because it can represent a list of individual elements. For example, (1,) represents a list that contains only 1, while (1, 2, 3,) represents a list that in turn contains a list of 1,2, and 3 separated by Spaces.

Maps

Maps represents a collection of key and value pairs where keys are used to find values. They can easily collect values into named groups, and these groups can be accessed dynamically. You won'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 separated by commas. The keys and values in Maps can be arbitrary SassScript objects. A map may have only one value associated with a given key (although that value can be a list). A given value may be associated with many keys.

Like Lists, the main operation of Maps uses the SassScript function. The map-get function is used to find values in the map, the map-merge function is used to add values to values in the map, and the @each instruction can be used to add styles to each key-value pair in the map. The sequence of key and value pairs in the map is the same as when the map is created.

Maps can also be used for anything a list 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, is treated as a nested list key1 value1, key2 value2. Lists cannot be treated as maps, except for empty lists. () represents a map with no key/value pairs, which can also be thought of as a list without elements.

Note that the keys for a map can be any Sass data type (even another map), and the syntax for declaring a map allows for any SassScript expression, which will be evaluated as a value to determine the keys.

Maps cannot be converted to pure CSS. Passing a value or argument to a CSS function as a variable will result in an error. Use the inspect($value) function to produce an output string, which is useful for debugging maps.

(Colors)

Any CSS color expression returns a SassScript color value. This includes a large number of named colors, and these name strings do not distinguish between quotation marks or not.

In compressed output mode, Sass will output a short color representation of CSS. For example, in compressed mode #FF0000 will output red, but blanchedalmond will output #FFEBCD.

A common problem that users encounter is that Sass likes to output the same format as the named color in other output modes, and when compressed, interpolating the color into the selector becomes invalid syntax. To avoid this, if they are to be used in the selection of construction, always give the named color.

Operations

All data types support equality operations (== and!). =). In addition, each type has its own special way of calculating.

Number Operations

SassScript supports standard arithmetic operations on numbers (addition +, subtraction -, multiplication *, division /, and modulo %). Sass mathematical functions retain units during arithmetic operations. This means that, just like in real life, you can't do arithmetic with different unit numbers (such as adding px and em units after a number), and multiplying two numbers with the same unit will produce a unit square (10px * 10px == 100px * px). Note that px * px is an invalid CSS unit and Sass will throw an error because you are trying to use an invalid unit in CSS.

Numbers support relational operators (<, >, <=, >=), and all types support equality operators (==,!). =).

Division sum/(Division and/)

CSS allows/to appear between attribute values as a way of separating numbers (e.g. font attribute, p.E.x2 {font:italic bold 12px/20px arial,sans-serif; }). Since SassScript is an extension of the CSS attribute syntax, it must support this while also allowing/for division. This means that, by default, if two numbers are separated by/in SassScript, they will appear the same way in the returned CSS.

However, there are three cases where/is resolved as division. These cover the vast majority of cases where division is done. 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 surrounded by parentheses, unless the parentheses are outside a list and the value is inside the parentheses.
  3. If the value is used as part of another arithmetic expression.

For example:

p { font: 10px/8px; // Native CSS, not used as division $width: 1000px; width: $width/2; // The variable is used as division width: round(1.5)/2; // Uses the function height: (500px/2); // Parentheses are used as division margin-left: 5px + 8px/2px; // + is used as the division font: (italic bold 10px/8px); // In a list, parentheses can be ignored. }

Compile to:

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

If you want to use pure CSS/with variables (i.e. / not as a division), you can insert them using #{}. For example:

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

Compile to:

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

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

  • When you subtract, you're always there-Leave Spaces on both sides.
  • When representing a negative number or unary negative operation, in-Contains a space before and no space after.
  • If in a whitespace separated list, you can use parentheses around the unary negative operation, such as in10px (-$var)Medium.

- The different meanings of priority are as follows:

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

  2. - Between two numbers without Spaces. That means it's a subtraction, so 1-2 is the same as 1-2.

  3. Literal numbers begin with a -. This indicates a negative number, so 1-2 is a list containing 1 and -2.

  4. - Between two numbers, with or without Spaces. This indicates subtraction, so 1 -$var and 1 -$var are the same.

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

Color Operations

The color values supported by all arithmetic operations are computed in segments, that is, the component values of red (red), green (green), and blue (blue) are computed in turn. For example:

p {
  color: #010203 + #040506;
}

Calculate 01 + 04 = 05, 02 + 05 = 07, and 03 + 06 = 09, and compile it as:

p {
  color: #050709; }

Often color functions are more useful than trying to use color arithmetic to achieve the same effect.

The arithmetic between numbers and color values is also segmented. For example:

p {
  color: #010203 * 2;
}

Calculate 01 * 2 = 02, 02 * 2 = 04, and 03 * 2 = 06, and compile as:

p {
  color: #020406; }

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

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

Compile to:

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

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

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

Compile to:

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

Internet Explorer filters require all colors including alpha layers, and the format must be fixed #AABBCCDD, using the ie_hex_str function can easily convert colors to the format required by Internet Explorer filters. For example:

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

Compile to:

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

String Operations

The + operation can be used for concatenation strings:

p {
  cursor: e + -resize;
}

Compile to:

p {
  cursor: e-resize; }

Note that if the quoted string is added to the unquoted string (that is, the quoted string is to the left of the +), then the result returned is the quoted string. Similarly, if an unquoted string is added to an quoted string (the unquoted string is to the left of +) then the result returned is an unquoted string. For example:

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

Compile to:

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

By default, when an operation expression is used with other values, Spaces are used as concatenators:

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

Compile to:

p {
  margin: 7px auto; }

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

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

Compile to:

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

In string interpolation, the Null value is treated as an empty string:

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

Compile to:

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

Boolean Operations

SassScript supports Boolean and, or, and not operations.

List Operations

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

Parentheses

Parentheses can be used to affect the order of operations (Fool's Wharf note: priority) :

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

Compile 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%);
}

Compile to:

p {
  color: #ff0000; }

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

Keyword Arguments

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

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

It's not concise enough, but it makes Sass code easier to read. Keyword arguments give functions a more flexible interface that doesn't make it difficult to use even if there are many arguments.

named arguments can be passed in any order, and arguments with default values can be omitted. Since named parameters are also variable names, underscores and dash lines can be used interchangeably.

See Sass::Script::Functions for a complete list of Sass functions and their parameter names, as well as steps on how to define your own functions in Ruby.

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

You can also use SassScript variables in selectors and property names via the #{} interpolation syntax:

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

Compile to:

p.foo {
  border-color: blue; }

It can also insert SassScript into property values using #{} interpolation statements. In most cases, this may not be as convenient as using a direct variable, but using #{} means that operators near it will be treated as pure CSS (Fool's Wharf note: all kinds of operations can be avoided). For example:

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

Compile to:

p {
  font: 12px/30px; }

In SassScript&(&in SassScript)

Just as when it is used in a selector, the & in SassScript points to the current parent selector. Below is a comma-separated list (list) that contains a single space. For example:

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

$the selector value is now ((" foo bar ". Baz. "bang"), "the BJP. Qux"). The 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 nested levels, so it guarantees access consistency.

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

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

Variable default:! default(Variable Defaults:! default)

If the value assigned to the variable is added after! The default flag, which means that the variable will not be reassigned if it has already been assigned, but if it has not, it will be assigned a new given value.

For example:

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

Compile to:

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

Pass! When default is assigned, if the variable is null, it is treated as unassigned (so the value of $content below is "Non-null content") :

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

Compile to:

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

@Rules and instructions (@-Rules and Directives)

Sass supports all CSS3 @ rules, as well as some other Sass specific "directives" known. These have corresponding effects in Sass, see the control directives and the mixin directives for more information.

@import

Sass extends the CSS@import rule 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 used in the main file (Fool's Wharf note: the value of the main file is the file that imported other files, that is, the file A imported the file B, here the main file refers to the file A).

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

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.

@import requires a file name to import. By default, it looks for a Sass file to import directly, but in the following cases, just as a normal CSS@import rule statement, no Sass files will be imported.

  • If the file extension is.css.
  • If the file name starts withhttp://Here.
  • If the file name isurl().
  • if@importContains any media queries.

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

For example,

@import "foo.scss";

or

@import "foo";

Both lines of code import the file foo.scss, while

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

Compile all as

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

Sass supports importing multiple files at the same time in a single @import rule. For example:

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

Import both rounded-corners and text-shadow files.

Import rules may contain #{} interpolation, but there are certain limitations. Cannot import Sass files dynamically through variables; #{} interpolation only applies to CSS import rules. Therefore, it only works with url() imports.

For example:

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

Compile into

@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 into 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. Then, there is no need to add underscores in the import statement.

For example, you might have a file named _colors.scss that doesn't compile into the _colors.css file. You can do that

@import "colors";

Thus, _colors.scss will be imported.

Note that you should not place underlined and ununderlined files with the same name in the same directory. For example, _colors.scss and colors.scss cannot exist in the same directory at the same time. Otherwise underlined files will be ignored.

nest@importNested@import

Although in most cases @import is usually used at the top of the document (outside of nested rules), it is also possible to include @import statements in CSS rules and @media rules. Just like a basic @import, this will contain the contents of the @import import file. However, the imported rules can only be nested where @import was originally prevented.

For example, if example.scss contains

.example {
  color: red;
}

Then (Fool Dock note: import into #main style)

#main {
  @import "example";
}

Fool's Wharf Note: After this import is equivalent to:

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

Will be compiled as

#main .example {
  color: red;
}

This directive is only allowed to appear at the top of the document (outside of the nested rules), like @mixin or @charset, in the file, and is not allowed to be imported into a nested context by @import.

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

@media

The @media directives in Sass behave the same as in pure CSS, with a little extra functionality: they can be nested within CSS rules. If an @media directive appears in a CSS rule, it bubbles to the top of the stylesheet and contains all selectors within the rule. This makes it easy to add specific media styles without reusing selectors or messing up the stylesheet writing stream. For example:

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

Compile to:

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

@media queries can also be nested within each other. These queries, when compiled, are combined with the and action symbol. For example:

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

Compile 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, @media queries can contain SassScript expressions (including variables, functions, and operators) in place 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; }}

Compile to:

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

@extend

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

<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 you must always remember to use.error when using.seriouserror. This is a burden on maintenance, can even lead to tricky errors, and leads to nonsensical styles.

The @extend directive avoids these problems by telling Sass that a style from one selector should inherit from another. For example:

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

Compile to:

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

.seriousError {
  border-width: 3px;
}

This means that.error says that all styles defined also apply to.seriouserror, except for certain styles for.seriouserror. Equivalently, every element with a.seriouserror class also has a.error class.

Others that use the.error rule also inherit to.seriouserror, for example, if we have a hack with a special error style:

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

Then

also uses the hacked.png background.

How it Works

@extend inserts an extension selector (for example,.seriouserror) in the stylesheet where the extended selector (for example,.error) 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;
}

Compile to:

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

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

.seriousError {
  border-width: 3px; }

@ the extend when merging selector will be very cleverly avoid unnecessary repetition, so like..seriouserror..seriouserror will convert..seriouserror, in addition, she won't generate cannot match any element selector (such as # main# footer).

Extending Complex Selectors

The Class selector is not the only one that can be extended; Sass allows any selector defined for a single element, such as.special.cool, a:hover, or a.ser [href^="http://"], for example:

class selection is not the only one that can be extended. She can extend any selector defined for a single element, such as.special.cool, a:hover, or a.ser [href^="http://"]. For example:

.hoverlink {
  @extend a:hover;
}

As with the class element, this means that the styles defined by a:hover also apply to.hoverlink. For example:

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

Compile to:

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

As with the.error.intrusion example above, all styles in a:hover will inherit from.hoverlink, even other styles that use her, such as:

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

Compile to:

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

Multiple Extends

The same selector can extend multiple selectors. This means that it inherits all the styles of the extended selector. For example:

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

Compile to:

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

.attention, .seriousError {
  font-size: 3em;
  background-color: #ff0; }

.seriousError {
  border-width: 3px; }

Each element with a.seriouserror class also has a.error class and a.attention class. Therefore, styles defined later in the document take precedence over styles defined earlier in the document: the background color of.seriouserror is #ff0, not #fdd, because.attention is defined after.error.

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

Chaining Extends

One selector can extend the selection of another selector, which in turn expands the selection of a third selector. For example:

.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, every element of the.seriouserror class will contain the.error class, and every element of the.criticalError class will contain not only the.criticalError class but also the.Error class. The code above compiles 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.bar or.foo +.bar, are not currently available as extensions. However, the selector sequence itself can use @extend. For example:

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

Will be compiled as:

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, which appears in another selector sequence. In this case, the two selector sequences need to be combined. For example:

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

It is technically possible to generate results for all matching conditions, but the resulting stylesheets are so complex that the simple example above might have 10 results. So, Sass will only compile the selectors that output something useful.

When two columns (sequence) are merged, two new selectors are generated if they do not contain the same selector: the first list is now before the second column, or the second list is now before the first column. For example:

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

Compile to:

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

If two columns (sequence) contain the same selector, the same parts will be combined and the other parts will alternate output. In the following example, both columns contain #admin, and they are combined in the output:

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

Compile to:

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

@extend-Only selector (@extend-Only Selectors)

Sometimes you just want to write a @extend extended style class that you don't want to use directly in your HTML. This is especially useful when writing a Sass style library, where you can offer @extend extended styles to users if they need them, and ignore them if they don't.

In this case, if you use a normal style class, there will be a lot of extra (useless) CSS in your final generated style sheet, and when HTML is used, it will easily cause conflicts when combined with other style classes. This is why Sass supports "placeholder pickers" (e.g., %foo).

Placeholder selectors look a lot like regular class and id selectors, just # or. Is replaced with %. It can be used like a class or id selector, but its own rules are not compiled into the CSS file. For example:

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

Placeholder selectors, like class and id selectors, can be used for extensions. The extension selector will compile to CSS, the placeholder selector itself will not compile. For example:

.notice {
  @extend %extreme;
}

Compile to:

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

! optionalMark (The! optionalFlag)

Usually, when you extend a selector, you'll get an error if @extend doesn't work. For example, if you don't have a.notice selector and you write a.important {@extend.notice}, you get an error. If only one selector, h1.notice, contains.notice, then an error will also be reported. Because h1 conflicts with a, and no new selector is generated.

However, sometimes it is desirable to @extend without generating any new selectors. Just add after the selector! The optional logo is fine. For example:

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

In instruction@extend (@extend in Directives)

There are some limitations to using @extend in directives (such as @media) : Sass cannot extend CSS rules outside the @media layer to CSS inside the directive layer, which would generate a lot of useless code. This means that if @extend is used in @media (or any other CSS directive), it must be extended to a selector 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; }}

Hopefully, one day, browsers will natively support the @extend directive, so that extensions can be used in @media and other directives.

@at-root

The @at-root directive causes one or more rules to be restricted to output at the root level of the document instead of 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 with a block of code that contains multiple selectors:

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

This will output the following:

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

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

By default, @at-root simply excludes selectors. However, it can also use @at-root to move the selector outside of a nested directive such as @media. For example:

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

Generated:

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

You can use @at-root (without:...) Moves the rule outside of any instruction. You can also do this with multiple directives, as long as they are separated by Spaces: @at-root (without: media supports) moves the rule outside of @media and @supports queries.

There are also two special values that you can pass to @at-root. "rule" is a normal CSS rule; @at-root (without: rule) is equivalent to @at-root without query. @at-root (without: all) means that the style should be moved outside of all directives and CSS rules.

If you want to specify which directives or rules are included, rather than which should be excluded, you can use with instead of without. For example, @at-root (with: rule) moves the rule outside of all instructions, but stays inside CSS rules.

@debug

The @debug command prints the value of the SassScript expression to the standard error output stream. This is useful for debugging Sass files with complex SassScript expressions. For example:

@debug 10em + 12em;

Output:

Line 1 DEBUG: 22em

@warn

The @warn instruction prints the value of the SassScript expression to the standard error output stream. This is useful for warning users to deprecate the library or for fixing minor errors in mixins. There are two main differences between @warn and @debug:

  1. You can use--quietCommand line option or:quietThe Sass option turns off warnings.
  2. The style sheet trace will be printed out along with the message, so that users can see where their style raises a 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

The @error directive throws the value of a SassScript expression as a fatal error, including a nice stack trace. This is useful for validating the parameters of mixins and functions. For example:

@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 several variations of the same style.

Note: Control instructions are an advanced feature that is not commonly used in daily writing, and are mostly used in mixins instructions, especially in libraries like Compass.

if()

The built-in if() function lets you handle the branch in one condition and return two possible results. It can be used in any scripting context. The if function evaluates only one of the corresponding arguments and returns it - this allows you to refer to variables that have already been defined or can be evaluated, otherwise it would cause an error (for example, dividing by zero).

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

@if

The @if directive requires a SassScript expression and nested styles to be used under it. If the expression returns a value other than false or null, the following curly braces are returned:

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

Compile to:

p {
  border: 1px solid; }

The @if statement can be followed by multiple @else if statements and one @else statement. if the @if statement fails, Sass tries the @else if statement one by one until one succeeds, or if all fail, then the @else statement is executed. For example:

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

Compile to:

p {
  color: green; }

@for

The @for instruction repeatedly outputs a set of styles. For each repetition, the counter variable is used to adjust the output. The directive comes in two forms: @for $var from through and @for $var from to . Notice the difference between the keywords through and to. $var can be any variable name, such as $i; and are SassScript expressions that should return integers. When is larger than , the counter is decremented, not incremented.

The @for statement sets $var to each consecutive value within the specified range, and uses the value of $var in each nested style of output. For from... through, the range includes values and , but from... The to form runs from , but does not include the value of . Using the through syntax,

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

Compile to:

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

@each

The @each directive is usually formatted as @each $var in . $var can be any variable name, like $length or $name, and is a SassScript expression that returns a list or map.

The @each rule sets $var for each item in a list or map, and the output style contains the value using $var. For example:

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

Compile 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

The @each directive can also use multiple variables in the format @each $var1,$var2,... in . If is a list in a list (list), each element in the sublist is assigned its own variable. For example:

@each $animal, $color, $cursor in (puma, black, default), (sea-slug, blue, pointer), (egret, white, move) { .#{$animal}-icon { background-image: url('/images/#{$animal}.png'); border: 2px solid $color; cursor: $cursor; }}

Compile 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 is treated as a list of key-value pairs, multiple assignments work just as well. For example:

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

Compile to:

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

@while

The @while instruction repeats the output nesting style until the SassScript expression returns false. This can be used to implement more complex loops than the @for statement, but is rarely used for example:

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

Compile to:

.item-6 {
  width: 12em; }

.item-4 {
  width: 8em; }

.item-2 {
  width: 4em; }

Mixin Directives

mixin allows you to define styles that can be reused throughout the style sheet, avoiding the use of meaningless classes, such as.float-left. Mixins can also include all CSS rules, as well as anything else that is allowed in a Sass document. They can even take arguments, introduce variables, and output a variety of styles with only a few mixins of code.

Define a mixin:@mixin(Defining a Mixin:@mixin)

mixin is defined by the @mixin directive. It is followed by the name and optional arguments (arguments) of the blend, and the content block of the blend. For example, large-text blending is defined as follows:

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

Blending can also include a mix of selectors and attributes, and a selector can even contain parent references. For example:

@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 blend named add-column, you can use it as add_column and vice versa.

Reference mixed styles:@include(Including a Mixin:@include)

Use the @include directive to introduce mixins into a 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. For example:

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

Compile 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 rules (i.e., at the root of the document), as long as they do not directly define any properties or use any parent selector references. For example:

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

@include silly-links;

Compile to:

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

The mixin definition can also include other mixins. For example:

@mixin compound {
  @include highlighted-background;
  @include header-text;
}

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

Blending can include yourself. This behavior is different from previous versions of Sass 3.3, where blending recursion was prohibited.

A blend that defines only descendant selectors can safely blend into the top layer of the file.

Arguments

A mixin can take the SassScript value as a parameter, and the given parameter is included in the mixin and provided as a variable to the mixin.

When defining a mixin, parameters are written as variable names in parentheses following the name of the mixin, and multiple parameters can be separated by commas. Then, when the call is mixed in, the value is passed through the corresponding argument order. For example:

@mixin sexy-border($color, $width) {
  border: {
    color: $color;
        width: $width;
    style: dashed;
  }
}

p { @include sexy-border(blue, 1in); }

Compile to:

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

Mixins can also specify default values for parameters using the normal variable assignment syntax. Then, when the call is mixed in, if no parameter is assigned, the default value is automatically used instead. For example:

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

Compile to:

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

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

Keyword Arguments (Keyword Arguments)

mixin can also use explicit keyword arguments when introducing (@include directive). For example, the above example could 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 stylesheet easier to read. It presents a more flexible interface to functions, and it makes multi-argument blending easier to call.

Named parameters can be passed in any order, and parameters with default values can be omitted. Since named arguments 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 a function uses. For example, a mixin used to create a box-shadow can take any number of box-shadow parameters. For these cases, Sass supports "mutable arguments ", where the argument declares a mixin or the end of a function, and all remaining arguments are packaged into a list. Parameters look just like normal parameters, but are followed by... . For example:

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

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

A variable argument can contain any keyword argument passed to a mixin or function. These can be accessed using the keywords($args) function, which returns a map, a string of parameter names (no $), and a key-value pair of values.

Variable parameters, which can also be used when calling (@include directive) a mixin. Using the same syntax, you can extend the list of values so that each value is passed in as a separate argument, or extend the map of values so that each key-value pair is treated as a keyword argument. For example:

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

Compile 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 argument at the same time, as long as the list comes before the map, for example, @include colors($values...). , $map...) .

You can use variable parameters to wrap a mixin and add additional styles without changing the signature of the mixin's parameters. If you do this, the keyword arguments will be passed directly through the wrapped mixin. For example:

@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 Passing content blocks to a mixin

A block of style content can be passed to a location where the style is included in the mixin. The style content block will appear wherever the @content directive is mixed in. This makes it possible to define abstractions associated with selectors and instructions for parsing.

For example:

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

Generated:

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

The same mixin can be done in the.sass shorthand syntax (@mixin can be represented by =, while @include can be represented by +) :

=apply-to-ie6-only
  * html
    @content

+apply-to-ie6-only
  #logo
    background-image: url(/logo.gif)

Note: When the @content directive is specified multiple times or within a loop, the style block will be copied and referenced on each call.

Variable Scope and Content Blocks

A block of content passed to a mixin operates in the scope in which it is defined, not in the scope of the mixin. This means that local variables mixed in (mixin) cannot be passed to the style block for use, and the variables are resolved to global values:

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

Compile to:

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

In addition, this makes it clear that variables and the use of mixers passed into the block point to other styles around the block definition. For example:

#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. Such as

$grid-width: 40px;
    $gutter-width: 10px;

@function grid-width($n) {
      @return $n * $grid-width + ($n - 1) * $gutter-width;
}

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

It becomes:

#sidebar {
  width: 240px; }

As you can see, a function can access any globally defined variable, as well as accept parameters, like a mixin. Functions can contain statements, and you must call @return to set the return value of the function.

As with mixin, 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 functions to avoid naming conflicts, and that others reading the stylesheets know that they are not native to Sass or CSS. For example, if you work for ACME Corporation, you could name the above function -acme-grid-width.

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

For historical reasons, hyphens and underscores in function names (and all other Sass identifiers) are interchangeable. For example, if you define a function called grid-width, you can call it with grid_width, and vice versa.

Output Style

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

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

Sass allows you to choose between four different output formats by setting the :style option or using the --style command line flag.

:nested

The nested format is the default output format for Sass because its format reflects the CSS style and HTML document structure. Each attribute is exclusive to one row, but indentation is not fixed. Each rule is indented based on how deep it is nested. For example:

#main {
  color: #fff;
  background-color: #000; }
  #main p {
    width: 10em; }

.huge {
  font-size: 10em;
  font-weight: bold;
  text-decoration: underline; }

When reading large CSS files, the nested format is very useful: it allows you to easily grasp the structure of the file without having to read it in detail.

:expanded

The expanded format is more like a handwritten CSS style, with each attribute and rule using an exclusive line. Attributes inside the rule are indented, but the rule does not have any special indentation. For example:

#main {
  color: #fff;
  background-color: #000;
}
#main p {
  width: 10em;
}

.huge {
  font-size: 10em;
  font-weight: bold;
  text-decoration: underline;
}

:compact

compact formats take up less space than nested or expanded formats. This format focuses on the selectors, not their properties. Each CSS rule is exclusive to one line, which also includes each property defined. Nested rules start on a separate line, and unnested selectors output a blank line as a separator. For example:

#main { color: #fff; background-color: #000; }
#main p { width: 10em; }

.huge { font-size: 10em; font-weight: bold; text-decoration: underline; }

:compressed

The compressed format takes as little space as possible, there is a line feed at the end of the file, and in addition to the necessary separator selector, there is basically no extra space, it also includes other small compression, such as choosing the least color representation. This means poor readability. For example:

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

Extending Sass (Extending Sass)

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

Defining Custom Sass Functions (Defining Custom Sass Functions)

Users can customize Sass functions through the Ruby API, see the source code documentation for more information.

Cache Stores

Sass caches documents that have been parsed, which makes them reusable without having to parse them again unless they have been changed. By default, Sass writes these cache files to the filesystem specified by :cache_location. If you can't write to the file system or need ruby processes or computers to share the cache, you can define your own cache storage and set the :cache_store option. For more information about creating a custom cache store, see the source code documentation.

Custom Importers

The Sass import is mainly responsible for getting the paths passed to @import and finding the corresponding Sass code for those paths. By default, this code is loaded from the file system, but Importers can be loaded from a database, via HTTP, or added to Sass 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 the :load_paths array along with the normal file system paths.

When parsing an @import, Sass will look for an importer to successfully import the path through the load path. Once found, the imported file is used.

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