Sass write a rule but don’t create it. A Guide to SASS for Absolute Beginners


Hello friends!

This detailed guide by preprocessor Sass for beginners. Here we will get acquainted with the Sass preprocessor, its advantages, syntax and consider its use with examples.

Cool

Plus

Stammer

Issue sponsor - hosting partner: partnerwp.ru

You can download all Sass/CSS examples and the customized Gulp project for this tutorial from GitHub.

Sass- is one of the most developed and stable CSS preprocessors, as well as one of the most popular preprocessors among professionals.

Benefits of Sass

  • Compatible with different versions CSS, thanks to which you can use any CSS libraries in your project;
  • Great amount a variety of functions for every occasion. Few CSS preprocessors can boast such rich functionality;
  • Sass is one of the oldest CSS preprocessors, having absorbed a lot of experience over the many years of its existence;
  • A great opportunity to use Sass frameworks that make life easier for the developer. One such framework is Bourbon, which we use in some editions of Jedi when writing Sass;
  • Syntax. You can choose one of two syntaxes that is closer to you - simplified (SASS) and expanded CSS-like (SCSS).

When I first got acquainted with CSS preprocessors, I, like many other novice web developers, did not fully understand the idea using CSS preprocessors. Why make an additional layer, use some tools, complicate the CSS, I thought. But over time, I began to understand that day after day writing CSS became torture, a gray routine; many actions had to be repeated, selectors, properties, and even entire blocks of CSS code had to be copied to achieve the desired result. Today, using examples, I will show you how you can simplify your work using the Sass preprocessor, diversify your development, and even have a little fun writing some more or less complex functions.

Setting up the environment

As an environment for working with Sass in this lesson, as in our other lessons, we will use the Sass version for the Gulp task manager ( gulp-sass). To use the original Ruby version or compile Sass using special software, you can read the instructions at the office. website. This lesson is primarily practical in nature, so stop at possible options We won’t connect to the project; we’ll connect Sass in the most popular way, using Gulp.

Make sure you have installed latest version Node.js and Gulp. If Node.js is not installed, download it and install it. After installing Node.js, install gulp with the command "npm i -g gulp"(Windows) or "sudo npm i -g gulp"(Linux, OS X). Read: .

Npm i --save-dev gulp gulp-sass

Var gulp = require("gulp"), // Connect Gulp sass = require("gulp-sass"); // Connect the Sass package gulp.task("sass", function() ( // Create a task "sass" return gulp.src(["sass/**/*.sass", "sass/**/*.scss "]) // Take the source.pipe(sass((outputStyle: "expanded")).on("error", sass.logError)) // Convert Sass to CSS using gulp-sass .pipe(gulp.dest(" css")) // Upload the result to the css folder)); gulp.task("watch", function() ( gulp.watch(["sass/**/*.sass", "sass/**/*.scss"], ["sass"]); // Watch behind sass files in the sass folder)); gulp.task("default", ["watch"]);

Pay attention to line 6 - here we use one of the output styles to the resulting file: nested- nested, by default; expanded- expanded; compact- compact, when the selector and its properties in curly braces are displayed on one line; compressed- compressed. In addition, thanks to the processing .on("error", sass.logError) If an error occurs, we won't have to reload the Gulpfile execution command and we will see which line of the Sass file we have an error on. In the examples I will use the output style expanded for clarity.

You should have the following project structure in your file system:

  • myproject/
    • css/
      • common.css
    • sass/
      • common.sass
    • node_modules/
    • gulpfile.js
    • package.json

We start execution of Gulpfile with the command gulp in the project folder terminal.

Here we take all Sass files from the directory sass/ your project and upload the finished CSS result to a folder css/. In addition, here we establish an observation watch for changes in Sass files and automatic compilation into CSS, if such changes take place. The resulting css file is included in the layout.

If you are confused about setting up Gulp packages in this example, read the Gulp manual.

After our environment is configured and Sass is successfully converted to CSS when saving *.sass files in the directory sass/, you can safely continue learning and carry out the examples that we will analyze today in practice.

Sass Syntax

There are 2 variants of writing Sass, 2 syntaxes: SASS and SCSS. Most old version Sass writing is indentation syntax. This is the spelling we will use in our lesson. The file extension for this syntax is *.sass. The second option is the syntax, extending CSS syntax, Sassy CSS. SCSS is written like regular CSS, but extended additional features Sass. File extension with SCSS syntax - *.scss.

Very important! The indentation syntax requires very strict adherence to the indentation of nested properties, and if you experience errors when running Gulp or implicit errors without specifying a line in the console, most likely the error is in incorrect indentations. Another important detail - if you use tabs as indents, the compiler will throw an error when you try to convert Sass, which, in addition to tabs, also uses spaces as indents. Either you use only tabs or only spaces.

SASS and SCSS syntax:

SASS - Indentation Syntax SCSS - extension syntax
$font-stack: Helvetica, sans-serif $primary-color: #333 body font: 100% $font-stack color: $primary-color $font-stack: Helvetica, sans-serif; $primary-color: #333; body ( font: 100% $font-stack; color: $primary-color; )

Except basic rules spellings (curly braces, semicolons at the end of lines), SASS and SCSS also differ in the spelling of some functions. So be careful when using any examples from the Internet, check exactly what syntax is used. If a fairly large example from the Internet is made in SCSS style, and your project is written in SASS, you can import it into your main file without changing the syntax and file extension using the directive @import, for example, if you downloaded a file carousel.scss, then you can connect it to your main.sass line @import "carousel". You can also do the opposite situation, when you need to import *.sass files into the main.scss file. In our example from Github, we import everything _x.x.sass files into one common.sass, where x.x is the title number of the example from this article.

We will use the indentation syntax.

1. Extending CSS with Sass

1.1 Investment rules

Sass gives developers a great opportunity to nest CSS rules within others, thereby reducing the time spent writing/copying long selectors and making the code more structured, with a clear hierarchy.

1.2 Binding to a parent selector

If you want to extend the selector without creating a new rule, you can bind additional selectors to the finished selector using the sign & . On the surface this looks like creating a child selector in the hierarchy, but using & , we are extending the parent selector rather than creating a child one.

Pay attention to the rule body.firefox &, which allows us to get a new chain from any element before the current one if set at the end & .

Additionally, parent binding can be used to create compound selectors:

1.3 Nested properties

For convenience, you can break the property namespace suffix into attachments. For example, margin-top, margin-bottom margin-left, margin-right have common ground margin and can be broken down into attachments as follows:

1.4 Wildcard selectors

Sometimes a situation arises when several elements on a page use the same CSS base, the same set of properties, specific only to them. These basic CSS rules can be packaged as a wildcard selector for use in multiple places in Sass. Wildcard selectors are inferred using a directive @extend.

2. SassScript

SassScript allows you to significantly expand the capabilities of Sass through the use of custom variables, arithmetic and other functions. SassScript can be used to automatically generate new selectors and properties.

2.1 Variables in Sass

It's a really cool feature to be able to define variables that can be used anywhere in your Sass file. Colors, default values, units, all this can be taken into a variable and used in the future. The variable is defined like this: $name: value.

2.2 Operations with numbers and strings + interpolation

Sass gives you the ability to use standard arithmetic operations on numbers, such as addition (+), subtraction (-), division (/), and modulo (%). Comparison operators (<, >, <=, >=, ==, !=) are also supported for numbers.

In addition, Sass has the ability to concatenate (connect) strings.

As we can see from the example $summ: 10 + 20 / 2, priority is observed in performing arithmetic operations - first division, then addition. To define the order of operations, you can use parentheses, as in mathematics. Please note that when adding 12px + 8px, we will get 20px.

Also pay attention to lines 2 and 9, here we use interpolation to place dynamic values ​​​​anywhere in the Sass file, including in the place where we have the name of the property, the name of the selector, or on any line.

Interpolation- this is obtaining a new value using others.

The most common use of interpolation in Sass is to obtain a new value for a variable by "integrating" it into the value of another variable, through the construct #{} , For example:

You can't just insert a variable into a string without using interpolation, as you can do in PHP, for example, in double quotes. Be sure to use interpolation into variables.

2.3 Operations with flowers

Colors in Sass can be added, subtracted, divided, and multiplied. All arithmetic operations are performed for each color separately: red, green and blue.


Please note that when adding rgba colors, the last 0.75 opacity parameter must not be different from the others in the expression, otherwise the addition will fail. Instead, you can adjust the rgba alpha channel using opacify And transparentize or control the opacity of a HEX color using the rgba function.

3. Directives and rules

3.1 @import

You can import into your Sass file sass, scss And css files using directive @import, while all mixins and variables will work in the main file into which the import occurs.

@import will work like regular CSS @import if:

  • present in the path to the file http://;
  • the file is called via url();
  • or the import contains media parameters.

In order for another file to be fully imported into the main Sass file, the file extension must be *.sass, *.scss or *.css.

Let's look at some examples.

The following files are imported will not:

The following files will imported:

Attention! In new versions gulp-sass to import CSS files into Sass you need to specify the .css extension

It is possible to import multiple files, separated by commas: @import "header", "media".

Files that start with underscore, are called fragments and do not require underscores or extensions to be specified when importing. For example, file _header.sass can be imported like this: @import "header".

Note that the import occurs at the location where you specify the directive @import. Accordingly, it is possible to do nested imports in the place where it is necessary:
#main @import "example"

3.2 @at-root

Directive @at-root lifts the rules contained in it to the root, canceling the chain from the parent. Everything is simple here:

We did not look at all the directives that are in Sass, but only the most used in practice. If you're interested in diving deeper into Sass directives, check out the documentation.

4. Expressions

Sass supports the use of expressions and functions for various conditions, loop implementations, etc.

4.1 @if() Directive

Directive @if() allows SassScript to be executed under certain conditions and has the following syntax:

4.2 @for Directive

@for displays a block with styles a certain number of times. You can set a counter variable at runtime.

You can specify through instead of to, if you need to go from 1 to 11 inclusive, and not just up to 10, as in the example.

4.3 @each Directive

If you want to iterate through a list of values ​​rather than just numbers, you can use the directive @each:

4.4 @while Directive

@while loops through style blocks while the expression is true.

5. Mixins

Hagfish- Sass code blocks (or template mixins), which can take arguments (optional) and can significantly expand the possibilities of writing styles and reduce the time spent on applying similar rules and even entire CSS blocks. It's something like a function that can take an argument, do a huge amount of work, and produce a result depending on the input parameter.

A mixin is declared by a directive @mixin, after the announcement it must be indicated Name hagfish. Called by a mixin directive @include, which takes the name of the mixin and the passed arguments, if any.

Friends, we have looked at the main features of Sass, which are enough for fruitful work with CSS styles site. Some directives and features are not included in this guide, but if you are interested in learning about all the features of Sass, it will be useful.

I’ll answer the question right away - how to work with Sass styles on a finished website, is it really necessary to edit the finished CSS and upload it via FTP? No, you can't do that. You should have a local copy of your Sass styles or even the entire site and, after finishing work, deploy (upload) via FTP ready-made styles. For this, you can use the Gulp package vinyl-ftp. Or set up a Sass environment on your server to compile files uploaded via FTP/sFTP.

That's all for today. Thank you for your attention!

Hi all! How quickly time flies. I didn't even notice how I switched from writing styles from regular Css to the Sass preprocessor. But I didn’t understand before - what kind of Sass is, what is it needed for, it’s probably for super advanced pros in layout. Yes, using preprocessors is a step forward new level in web development, but there is nothing scary or complicated here and you will see for yourself after reading this article to end.

So, what is good about the preprocessor and Sass specifically? I will say right away that there are others, such as Less, Stylus, etc. They all work according to the same principle, but each has its own characteristics. Sass has gained great popularity among professionals, making learning much easier. It’s just that the more popular the technology, the larger the community and the more extensive the documentation.

Preprocessors are designed to relieve the developer of most routine tasks when writing code, thereby increasing the speed and quality of work. In addition to CSS preprocessors, there are also HTML preprocessors, for example, Pug (Jade).

Article structure

Documentation

The developer of Sass is the Frenchman Hugo Giraudel, who has been living in Germany for some time. Naturally the documentation is on English language, but I personally have a good grasp of it (it’s important to know technical English). But there is also a translation into Russian. I would still recommend the English version, this is in order to get used to it and study English more and more deeply. But the Russian one is no worse either.

  • English documentation: http://www.sass-lang.com
  • Russian documentation: https://sass-scss.ru

Compiling Sass to Css

As software To compile Sass to Css I use the Sass task manager plugin. In general, Sass is an application (Gem) Ruby language. Therefore, if you want to do without Gulp, then to compile to Css you will need to install the Ruby programming language platform. I won’t show you how this is done now, you can read about it on the official website.

Syntax - Sass, Scss

Let me immediately note that there are 2 syntaxes for writing code: Sass and Scss.

The syntax of Sass differs slightly from Scss. Scss looks more like normal css code, and Sass omits the curly braces and semicolons between rules. There are also differences in how some functions are written and you have to be careful about which syntax you choose. File extensions for Sass − *.sass, and for Scss - *.scss. Sass syntax is older, and Scss came later to make it easier for beginners to learn. I myself started studying this preprocessor in Scss, it was easier to understand it that way. Now I have switched to Sass, it is more convenient for me.

If we talk about Sass, then its code structure is built on the basis of indentations (after all, there are no curly braces in it) and you should be careful here, since both a tabulator (TAB - 4 spaces) and ordinary spaces (usually it's a double space). I always use a tabulator.

Remember! If you use a tab as an indent, then spaces should be excluded so that everything is the same. And vice versa - if you use spaces, then the tabulator should be excluded. Otherwise, the compiler will throw an error.

Sass

.maincontent .main-title font-size: 30px font-weight: 700 margin: 0 0 30px .description margin-bottom: 30px p color: #444444 font-size: 16px line-height: 22px

Scss

.maincontent ( .main-title ( font-size: 30px; font-weight: 700; margin: 0 0 30px; ) .description ( margin-bottom: 30px; p ( color: #444444; font-size: 16px; line -height: 22px; ) ) )

Most code editors (for example, Sublime Text) have indentation markings in the form of stripes, which prevents us from getting confused. In the examples below I will use Sass syntax.

Simplifying your life with Sass

Nesting of rules

This is what I liked about Sass from the very beginning, it was precisely the nesting of CSS rules one within another. This saves a lot of time, and the code is structured and easy to read. For example, if we want to write styles for elements of a specific parent container, then in Css we need to specify the parent class each time, for example like this:

Main .title ( font-size: 30px; color: #444; ) .main .subtitle ( font-size: 20px; ) .main .description ( font-size: 14px; margin-bottom: 30px; )

That is, we specify the parent class.main everywhere, and this, in turn, is not entirely convenient. Using Sass, you can write it like this:

Scss

.main ( .title ( font-size: 30px; color: #444; ) .subtitle ( font-size: 20px; ) .description ( font-size: 14px; margin-bottom: 30px; ) )

Sass

.main .title font-size: 30px color: #444 .subtitle font-size: 20px .description font-size: 14px margin-bottom: 30px

Agree, it looks much neater, and you can write code faster, because we write the parent class.main only once. If you want to follow me without installing Ruby and any similar software, you can use the online compiler for a demonstration.

Nested properties

In addition to nesting rules in Sass, there is the possibility of nesting properties. For example, here's how to write margin values:

Sass

.main .title margin: top: 10px right: 15px bottom: 10px left: 15px

Css

.main .title ( margin-top: 10px; margin-right: 15px; margin-bottom: 10px; margin-left: 15px; )

Selector binding or concatenation - & sign

We can speed up writing our code and make it even more compact by using concatenation (connection) using the symbol - & . How it works? For example, we have classes such as: .main-title, .main-subtitle, .main-description. In Sass, these classes can be written as follows:

Main &-title font-size: 30px color: #444 &-subtitle font-size: 20px &-description font-size: 14px margin-bottom: 30px

Main-title ( font-size: 30px; color: #444; ) .main-subtitle ( font-size: 20px; ) .main-description ( font-size: 14px; margin-bottom: 30px; )

Using a symbol & we connect to the root class, that is, in this case there is no need to constantly repeat root.main . At the same time, keep in mind that we have not created any child elements.

/* Link */ a ( color: red; ) a:hover ( color: blue; ) /* Pseudo-elements */ .main::before ( content: ""; display: block; font-size: 20px; ) .main ::after ( content: ""; display: block; font-size: 30px; )

Sometimes you need to specify a chain of selectors up to the current element. You can, of course, move it to the root, but in order not to break the nesting, you can write it as follows:

Main .container & width: 700px

Container.main (width: 700px)

By moving & after the selector, we changed the docking order, i.e. the class.container in this case is the parent.

Binding to the parent selector, but one level higher

Above, as an example, I demonstrated Sass code:

Main &-title font-size: 30px color: #444 &-subtitle font-size: 20px &-description font-size: 14px margin-bottom: 30px

Now imagine that in the .main-title block there is another element that needs to be explicitly styled using the entire chain of parents. For a long time I simply specified the root name (in this case - .main), but this is not very convenient. I started poking around the Sass documentation and found a solution. In fact, everything is simple - we need to declare a link to the parent and use it where necessary.

This is how I did it before:

Main &-title font-size: 30px color: #444 .main__icon // specify the root.main, otherwise, if you use & it will link to .main-title color: #444 width: 20px &-subtitle font-size: 20px & -description font-size: 14px margin-bottom: 30px

And now you can do this:

Main $self: & // link to the parent &-title font-size: 30px color: #444 #($self)__icon // instead of & use a link to the parent color: #444 width: 20px &-subtitle font-size: 20px &-description font-size: 14px margin-bottom: 30px

If you noticed, we declared a reference to the parent - $self: & . This reminds me a bit of a reference to the object (this) that triggered the event in JavaScript. Now, in the right place, we can simply call it #($self) . It turns out how simple it all is, but I was scratching my head and thinking that there was no solution to this problem in Sass.

Main-title ( font-size: 30px; color: #444; ) .main-title .main__icon ( color: #444; width: 20px; ) .main-subtitle ( font-size: 20px; ) .main-description ( font-size: 14px; margin-bottom: 30px; )

Templates

It often happens that several elements have the same style base, but differ from each other in only a few rules. Let's take buttons for example. If we take the same size of buttons, then they can differ from each other only in color: red, green, gray, etc. If you use pure Css, you will have to specify all the button colors in the base styles, separated by commas, or create a base class. But in Sass it's much easier:

%button background-color: #666 border: 1px solid #666 padding: 0 20px font-size: 15px line-height: 40px height: 40px .button-green @extend %button background-color: green border-color: green . button-red @extend %button background-color: red border-color: red

Button-green, .button-red ( background-color: #666; border: 1px solid #666; padding: 0 20px; font-size: 15px; line-height: 40px; height: 40px; ) .button-green ( background-color: green; border-color: green; ) .button-red ( background-color: red; border-color: red; )

The template in this case is the %button selector (this is indicated by the - %) sign. This is convenient because the template selector itself is not involved anywhere, and its styles are inherited by other selectors through the directive - @extend. This template can be used as many times as you like, thereby reducing the amount of code.

SassScript

In Sass, as in programming languages, there are such features as: creating variables, arithmetic operations (addition, subtraction, division, multiplication, etc.), iterations (loops), functions (mixins) and much more. That is, Sass is a kind of programming language, which is again designed to simplify writing code and speed up work significantly.

Variables

A variable in Sass starts with a sign $ , and the name is written in Latin, for example: $color . It should be noted that the signs: “ " And " _ » are interchangeable. For example, if you called $color-red , then you can call $color_red . The variable is defined as follows: $name: value, for example: $color: #f6f6f6 .

A variable declared outside of any nesting levels is available globally, i.e. can be used everywhere. If you define a variable at any nesting level of the selector, then it will be available only at this level. For it to work globally throughout the document, you must specify a keyword !global.

Title $font-size: 10px !global font-size: $font-size .subtitle font-size: $font-size

In general, variables are a wonderful thing; you just need to declare them and enter a value, and then you can use them as much as you want, anywhere. For example, we can define colors by giving them specific names, font size, font family, etc. and any meanings in general.

Directives

@extend

We touched on this directive above when we studied the blank template. Let's consolidate our knowledge again. By using @extend we can copy the rules of any selector. For example, during layout it may be that the element “ A" and the element " B"may be similar in appearance. In this case, you can write rules for element “A”, and for “B” you can simply copy the styles of element “A”, slightly redefining the necessary properties.

Block_a background-color: #cccccc border: 5px solid #999999 padding: 20px font-size: 30px height: 150px width: 150px .block_b @extend .block_a padding: 15px

Block_a, .block_b ( background-color: #cccccc; border: 5px solid #999999; padding: 20px; font-size: 30px; height: 150px; width: 150px; ) .block_b ( padding: 15px; )

In this example, we made 2 identical squares. For square “B” we only redefined the padding: 15px. This is how @extend works. I use this directive quite often.

@import

This directive allows you to combine several style files into one. This is very convenient, especially if the project is large. Not to be confused with the directive that exists in Css - @import. In Css, the required attribute is − url().

In fact, it is more convenient to write styles in different files and each has its own purpose. For example, the entire page framework can be divided into regions: header.sass, sidebar.sass, footer.sass. You can collect everything in the main file main.sass using @import. Region files can also be specified using an underscore at the beginning of the file name, for example: _header.sass, _sidebar.sass, _footer.sass. Such files are called fragments. When importing fragments, it is not necessary to specify the file extension.

Simple import

@import "header.sass" @import "sidebar.sass" @import "footer.sass"

Importing fragments

@import "header" @import "sidebar" @import "footer"

Fragment files can have the following extensions: *.sass, *.scss or *.css. For example, the main file could have the extension *.sass, and the site header, for example, with the extension *.scss. That is, it doesn’t matter what extension your main file has. It should be noted that when importing, all variables and mixins (we'll talk about them below) are transferred to the main file into which the import occurs.

You can also specify the import of several files separated by commas: @import “header”, “sidebar”, “footer”.

Keep in mind that the import occurs in the place where you specified the directive @import. This is usually done at the beginning of the document.

@at-root

Directive @at-root speaks for itself and if translated into Russian, it will sound like this - "from the root". In other words, we move the selector to the root, undoing the chain of parent selectors. Here, of course, you can ask the question: “Why is this directive needed if you can move the selector to the root manually?” The answer is simple - the convenience of writing code without breaking the structure. When you learn to work with Sass to its fullest extent, you will understand this.

Main &-title font-size: 30px color: #444 @at-root .main__icon color: #444 width: 20px

Main-title ( font-size: 30px; color: #444; ) .main__icon ( color: #444; width: 20px; )

Control Directives and Expressions

@if directive

This directive executes styles if the expression enclosed in it returns any value except false And null.

$color: green .header @if $color == green background-color: green @else if $color == blue background-color: blue @else background-color: #f6f6f6

Header ( background-color: green; )

Those who are familiar with at least the basics of a programming language (for example, javaScript or Php) will not find it difficult to understand. The essence here is the same, the main thing is to know the syntax of writing code.

@for directive

In a programming language (again in Javascript or Php) using For you can set a cycle. In Sass, this directive does the same thing - it creates a loop. For each iteration (repetition), a counter variable is used that changes the output data.

The directive has 2 forms of writing: 1. @for $var from<начало>through<конец>and 2. @for $var from<начало>to<конец>. If you want the last digit to be included in the loop, then use " through". Let's look at an example:

@for $i from 1 to 6 .elem-item-#($i) background-image: url("images/image-#($i).jpg")

Elem-item-1 ( background-image: url("images/image-1.jpg"); ) .elem-item-2 ( background-image: url("images/image-2.jpg"); ) . elem-item-3 ( background-image: url("images/image-3.jpg"); ) .elem-item-4 ( background-image: url("images/image-4.jpg"); ) . elem-item-5 ( background-image: url("images/image-5.jpg"); )

To specify the final value I used the keyword " to". In this situation, the cycle ends at the number - 5 . Notice how compact the Sass code looks.

@each directive

Directive @each just like @for, it displays values ​​in a loop and is convenient because, in addition to numbers, you can iterate over specific values. Let's take the above loop and change it to some values.

@each $bgItem in animal, lake, sea, landscape, nature .elem-item-#($bgItem) background-image: url("images/image-#($bgItem).jpg")

Elem-item-animal ( background-image: url("images/image-animal.jpg"); ) .elem-item-lake ( background-image: url("images/image-lake.jpg"); ) . elem-item-sea ( background-image: url("images/image-sea.jpg"); ) .elem-item-landscape ( background-image: url("images/image-landscape.jpg"); ) . elem-item-nature ( background-image: url("images/image-nature.jpg"); )

In this case, a counter variable is not created, and the number of iterations depends on the number of created values ​​after the keyword " in". The values ​​are output through a variable (in this example - $bgItem), the name of which can be arbitrary.

Mixins (functions)

Mixins (mixins) are a kind of function, like in a programming language, which is designed to get rid of repetitive code. Mixins can contain entire styling snippets, which are allowed in Sass. Let's look at an example for greater clarity.

@mixin align-center position: absolute top: 50% left: 50% transform: translate(-50%, -50%) .container @include align-center

A mixin is created with the @mixin directive, followed by a space separated by the name of the mixin, as well as optionally passed parameters. Let me immediately note that the hyphen (-) and underscore (_) signs in the mixin name are interchangeable. A mixin can contain not only rules, but also selectors. Above I gave an example of an elementary mixin without parameters.

The mixin is called with the @include directive and then, separated by a space, we indicate the name of the created mixin. In the example above, this is centering the block along the X axis and the Y axis using absolute positioning. If you have to use this often, then you will agree that it is easier to just call a mixin than to write centering styles over and over again.

Now let's look at a mixin with parameters (arguments).

@mixin border($width, $color) border: width: $width style: solid color: $color .square @include border(2px, #ccc)

Square ( border-width: 2px; border-style: solid; border-color: #ccc; )

As you can see, after the name of the mixin in parentheses we specify the arguments, in this case the border width and color. This is the simplest mixin that I provided for clarity. In practice, you can find more complex mixins using various conditions and variables. But let’s not complicate everything now; we should always start with something small and simple, and then move up as we move up.

With this I want to complete my short review Sass preprocessor. Why small? Yes, because this is not all that I told you. In general, using the above, you can safely start using Sass instead of Css now. You can learn more about Sass by referring to the documentation I provided above.

Well, thank you all for your attention! As always, ask questions in the comments and subscribe either to the telegram channel or to the email newsletter (form in the sidebar on the right) so as not to miss anything interesting.

See you in my other posts...

Combine programmability with flexibility

If you're developing cascading style sheets, Sass can make the process a lot easier. Sass is a cascading style sheet language and preprocessor that adds traditional programming attributes to CSS. Sass provides a number of programming features, including variables, logical nesting of styles, mixins, arguments, and inheritance. If you're creating style sheets for your Web site, Sass can make your life a lot easier by getting standard CSS markup by converting the Sass code.

In this article, you will learn about the key principles of Sass. The article contains practical examples, demonstrating how you can make CSS development easier and faster with Sass.

Sassy CSS Syntax (SCSS) is an extension of CSS3; any SCSS code is valid CSS code. All examples in this article are written in SCSS.

Why Sass

Sass Syntax
  • SCSS is the most common syntax and is an extension of CSS syntax.
  • .sass is an older syntax in which nested elements are implemented using indentation.

Sass is a robust, configurable, and feature-rich CSS development solution. Instead of outdated static CSS rules, it uses the principle of dynamically generating structures. If you want to stick to your programming style and have access to programming language structures, then Sass is the best choice.

CSS preprocessors have all the features needed for any Web development environment. They allow:

  • Reduce development time.
  • Implement the DRY (Don't Repeat Yourself) principle when developing CSS.
  • Make your code cleaner and more understandable.

There are many technologies pre-treatment CSS. In this article, we chose Sass because of its flexibility and breadth of capabilities.

Installing Sass

The main implementation of Sass is done in Ruby, although other implementations exist. The first step is to install Sass through its Ruby components.

  1. Download and install Ruby if it is not already installed on your system.
    • For Windows users: Download the Ruby installer for Windows.
    • For Mac users OS X: Ruby is already installed on your operating system.
    • For Linux users: Install Ruby using any package manager.
  2. Install the gem package Ruby Sass using the gem install sass command.

Preparing a Working Sass Environment

Create a file with the .scss extension in any text editor. Sass syntax support (color highlighting of different code fragments) varies between text editors; You will find a list of editors in the section.

Copy the code from Listing 1 and paste it into the generated scss file.

Listing 1. Sass code example
#blueBar ( position: relative; height: 37px; left: 0; right: 0; top: 0; )

The Sass language is an extension of CSS3. As of Sass version 3.2.1, any working CSS code is also working Sass code. An example of such code is shown in Listing 1. However, the Sass code in Listing 1 must be converted to CSS or Web browsers will not be able to interpret the style sheet correctly. Instead of constantly manually converting Sass to CSS using the sass-convert command, we'll configure Sass to automatically convert the sass file to CSS when we save it. To have Sass constantly monitor the file in question, run the command in Listing 2 at the command prompt.

Listing 2. File tracking
sass --watch style.scss:style.css

You can also configure Sass to monitor an entire directory, as shown in Listing 3.

Listing 3. Directory tracking
sass --watch stylesheets/sass:stylesheets/compiled

Now Sass will automatically convert your code into working CSS code when you save the sass file, and we can get started.

Variables

Variables are a key functionality that CSS lacks. Style sheets use a lot of repetition, so it's very useful to be able to set a specific value once and then reference it later. Let's say you have a style sheet similar to the one in Listing 4.

Listing 4. Defining the color of elements in CSS
#someElement ( color: #541B32; ) #anotherElement ( color: #541B32; ) #yetAnotherElement ( color: #541B32; )

Standard CSS markup requires all values ​​to be specified explicitly, which results in repetition in Listing 4. With Sass, you can use more effective method, as shown in Listing 5.

Listing 5. Listing 5. Defining the color of elements in Sass
$purplishColor: #541B32; #someElement ( color: $purplishColor; ) #anotherElement ( color: $purplishColor; ) #yetAnotherElement ( color: $purplishColor; )

The advantage is obvious. Now you can change the color of all elements in one place. Listing 5 contains a $purplishColor variable whose value can be changed in the Sass file at any time. Sass variables don't have types; String and integer values ​​and even color codes can be assigned to the same variable.

Modules

CSS code can be easily broken down into separate modules that the Sass engine will put together. You can import modules using the @import directive, as shown in Listing 6. The directive must include a file name, a hyperlink, or any other path. You can combine CSS and SCSS files simultaneously in one document.

Listing 6. Importing modules into Sass
@import "colors.scss" @import "links.scss"

The approaches to dividing code into modules in CSS and Sass are significantly different. When you break your CSS code into smaller style sheets, each style sheet requires a separate HTTP request to load. In Sass, the @import directive loads the module code immediately, so you always end up with a single CSS file.

Strings and substitution

Sass supports string concatenation and variable substitution. Instead of using variables only to assign values ​​to properties, you can also directly insert their values ​​into property and selector names, as shown in Listing 7.

Listing 7. Actions with strings and variables in Sass
$image_dir: "images/web/"; $page: 10; .button ( background-image: url($image_dir + "image.gif"); :before ( content: "Page #( $page )"; ) )

Listing 8 shows the code from Listing 7 converted to CSS.

Listing 8. Actions with strings and variables in CSS
.button ( background-image: url("images/web/image.gif"); ) .button:before ( content: "Page 10"; )

Mathematical calculations

Sass supports standard math operations on numbers, as shown in Listing 9. You can perform simple math operations on variable values.

Listing 9. Mathematical operations with numbers in Sass
.block ( $block_width: 500px; width: $block_width - (10px * 2) - (1px * 2); )

Listing 10 shows the code from Listing 9 converted to CSS.

Listing 10. Mathematical operations with numbers in CSS
.block (width: 478px; )

Mathematical operations with color codes are also supported, as shown in Listing 11.

Listing 11. Mathematical operations with color codes in Sass
.block ( $color: #010203; color: $color; border-color: $color - #010101; )

Listing 12 shows the code from Listing 11 converted to CSS.

Listing 12. Mathematical operations with CSS color codes
.block ( color: #010203; border-color: #000102; )

Nested selectors and properties

One of the most requested features missing from CSS is nested selectors (applying a style to a selector inside another selector). To create a nested selector in CSS, you must re-specify the parent selector for each child selector you define. Sass simplifies the process of creating nested selectors, as you can see in Listing 13.

Listing 13. Nested selectors in Sass
#some ( border: 1px solid red; .some ( background: white; ) )

Listing 14 shows the code from Listing 13 converted to CSS.

Listing 14. Nested selectors in CSS
#some ( border: 1px solid red; ) #some .some ( background: white; )

Control directives

Sass control directives build data flow and logic into CSS code. In this section we will look at the main control directives - @if, @for and @each.

@if

Sass supports basic functions if/else that can be compiled into CSS. Consider Listing 15, where we want to make the link color black in all cases except when the base color is already black. If the base color is already black, then we change it to white. Listing 15. Sass @if example

Listing 15. Example @if directive in Sass
$color:black; .link ( @if $color == black ( color: white; ) @else ( color: black; ) )

Listing 16 shows the code from Listing 15 converted to CSS.

Listing 16. Example of an @if directive in CSS
.link(color:white;)

Here the @if directive works the same as in other programming languages. After the @if statement, you can specify multiple @else if statements and one @else statement. If the @if condition is not satisfied, then the @else if statements are attempted one at a time until one succeeds or the @else statement block is reached.

@for

The @for directive generates a set of styles cyclically. Each iteration uses a counter variable, as shown in Listing 17.

Listing 17. Example @for directive in Sass
@for $i from 1 through 5 ( .button-#($i) ( width: 1px * $i; ) )

Listing 18 shows the code from Listing 17 converted to CSS.

Listing 18. Example of @for directive in CSS
.button-1 ( width: 1px; ) .button-2 ( width: 2px; ) .button-3 ( width: 3px; ) .button-4 ( width: 4px; ) .button-5 ( width: 5px; )

@each

The @each directive reads elements from the specified list and generates styles using their values, as shown in Listing 19.

Listing 19. Example of @each directive in Sass
@each $company in IBM, Motorola, Google ( .#($company)-icon ( background-image: url("/images/#($company).jpg"); ) )

Listing 20 shows the code from Listing 19 converted to CSS.

Listing 20. Example of an @each directive in CSS
.IBM-icon ( background-image: url("/images/IBM.jpg"); ) .Motorola-icon ( background-image: url("/images/Motorola.jpg"); ) .Google-icon ( background -image: url("/images/Google.jpg"); )

Functions

You can use functions in Sass. Consider abstracting and breaking the methods into separate pieces of code so they can be portable and used in other projects.

Sass has a lot of built-in functionality. For example, control functions rgb color() and darken() , shown in Listing 21. These functions can be used to change hue, saturation, brightness, transparency, fade scale, and many other color properties. You can also define your own functions and use them as needed.

Listing 21. Functions in Sass
#someElement ( color: rgb(150, 50, 100); ) #someDarkYellowElement ( color: darken(yellow, 33%); )

Listing 22 shows the code from Listing 21 converted to CSS.

Listing 22. CSS functions
#someElement ( color: #963264; ) #someDarkYellowElement ( color: #575700; )

Sass also contains mathematical functions, functions for working with strings and lists, introspection functions, and many others. You will find a complete list of functions in the section.

Hagfish

Mixins (reusable pieces of CSS code) are defined using the @mixin directive, as shown in Listing 23. Mixins can define patterns of property-value pairs and use them in other rulesets. Using mixins simplifies stylesheet code and makes it easier to read. Essentially, @mixin is a user-defined function. Mixins can also take arguments, meaning that with a small number of mixins you can create a variety of styles.

Listing 23. Mixins in Sass
@mixin rounded-corners($radius: 5px) ( border-radius: $radius; -webkit-border-radius: $radius; -moz-border-radius: $radius; ) #header ( @include rounded-corners; ) #footer ( @include rounded-corners(10px); )

Listing 24 shows the code from Listing 23 converted to CSS.

Listing 24. CSS mixins
#header ( border-radius: 5px; -webkit-border-radius: 5px; -moz-border-radius: 5px; ) #footer ( border-radius: 10px; -webkit-border-radius: 10px; -moz-border -radius: 10px; )

Mixins are similar to functions and can also work with variables. The difference between a mixin and a function is that a function always returns a value, while a mixin always returns lines of code.

Compass

Compass is an Open Source CSS development framework using the Sass language. Reusable design patterns (based on mixins) allow you to create rich and powerful style sheets. The Compass library of core functions is necessary tool when developing in Sass.

Essentially, Compass is a wrapper for CSS. Through CSS sprites and a number of other technologies, Compass takes care of common CSS problems, such as browser compatibility, schemas, and stylesheet optimization.

Like Sass, Compass is distributed as a Ruby gem package. To install Compass, run gem install compass on the command line.

You can then use Compass's defined mixins (functions), as well as many built-in CSS3 functions, classes, and supported features. For more information about Compass, see .

Conclusion

This article introduced you to several concepts that can help you successful implementation Sass code on your website. You learned about variables, substitutions, nesting, functions, and some directives.

Sass is not the only CSS preprocessor. Its closest competitor, LESS (see section), also enjoys some popularity. By and large, there are not that many differences between Sass and LESS. The main advantage of Sass is Compass, an extension that LESS does not have. It's important to work with as many CSS preprocessors as possible to understand which one is best for your needs.

27.07.2017

This series of SASS tutorials is intended for beginners and experienced developers. This is the first of a four-part tutorial that will walk you through the preprocessor, install it, and learn about some of its features.

What is SASS?

SASS (Syntactically Awesome Style Sheets)- one of the most popular. It is a set of CSS functions that allow you to code faster and more efficiently. SASS supports integration with Firefox Firebug. SassScript allows you to create variables, nested styles, and inherited selectors.

SASS makes it quick and easy to write less (sometimes significantly less) CSS code and dynamically manage it like a programming language (it's not a programming language, by the way). It's a great tool for writing more functional and cleaner CSS that can speed up the workflow of any designer and developer.

Why do you need SASS?

Most front-end frameworks, including Bootstrap, Materialize and Foundation, are built with this excellent preprocessor. Knowing SASS will help you use more features of these frameworks.

How to use SASS?

There are many applications that make it easy and quick to start using SASS: CodeKit, Compass, Koala, etc. You will learn about them in other parts of the tutorial. In this chapter, we will not use any applications or tools other than those needed to run SASS on a computer. You won't have to worry about the operating system because everything will be clear to all users.

Download and Install SASS

You can only install SASS on a machine that already has Ruby installed:

  • Ruby comes pre-installed on Mac, so you can install Sass Macintosh right away;
  • If you're on Windows, you'll need to download Ruby first;
  • Ruby on Linux can be downloaded through the apt package manager, rbenv or rvm.

Once Ruby is installed, you can install SASS on your machine. Let's open a Ruby command line and install SASS on your system:

Gem install sass

If the command above doesn't work, then you may have to use the sudo command:

Sudo gem install sass

If you want to check the SASS version use the following command:

SASS is installed. Let's create a project folder and call it sass-basic. Create a basic html file with the following code:

My First SASS Project

My First SASS Project

Hello friend I am learning SASS and it's really awesome.

Body( text-align: center; ) h1( color: #333; ) p( color: #666; )

Now you need to compile this file using the command line/terminal. Let's open a command prompt in the same directory (you may have to use the Ruby command prompt if the regular command prompt doesn't work). Type the following and press Enter:

Sass --watch style.scss:style.css

You will notice that new files have been generated: style.css and style.css.map. It is worth noting that you do not need to touch the map file, just like the .css file. If you want to make any changes, you can do this through style.scss. You don't need to repeat this process every time you change styles. SASS compilation will work automatically when you make changes to the .scss file.

In the next chapter, we'll look at SASS variables and why they are the most useful feature in SASS (and any other CSS preprocessor).

The article "SASS for designers and more" for 2013-02-21 has been renamed to " SASS Syntax" and updated (2014-02-17)

Sass- this is a preprocessor language; preprocessors compile the CSS code that we write in the processor language (SASS) into pure CSS code.

SASS documentation is aimed more at programmers, so designers are not always willing to start working with SASS. Additionally, the benefits of using SASS from a designer's perspective are not always clearly stated.

In this article I want to cover a few simple principles. I'm not a SASS expert, but I must point out that using sass is a wise decision.

So what are these benefits? You will be able to logically structure your code, thereby speeding up the process of writing code; the number of repetitions will be significantly reduced (variables will help us with this), the code will become much easier to maintain. The SASS language makes it easy to work on a project, no matter who you are - a programmer or a designer. This is true.

Variables

In SASS the name variable begins with a dollar sign ($). The variable values ​​are identical to the CSS property values.

Let's start with the basics, namely variables. Let's look at variables based on following example. We tend to use multiple colors in a document. As a result, you have to write color values ​​in hex or rgb format over and over again. If we want to change any color, we will have to auto-replace throughout the document. However, we cannot be sure that we will not capture an unnecessary value.

A (color: #822733;).summary (color: #822733;).copyright (color: #822733;)

For example, you can have several rules that determine the color dark red for the desired selectors. The SASS language allows us to do the following: at the beginning of the document, we can define a variable called $brand-colour and then in the document, instead of the value itself, put the name of the variable. Then, if we need to change the color, we just need to change the value of the $brand-colour variable and this will change the color of all rules that use the $brand-colour variable.

// My SASS color library $brand-colour: #822733; a (color: $brand-colour;).summary (color: $brand-colour;).copyright (color: $brand-colour;)

Numerical values ​​for variables

Variables can contain not only strings, but also numbers that you can manipulate. If you use grids or your layout scales based on specific values, then you probably use these values ​​throughout your style file. For example, if you constantly use a value of 10px, then you could define a variable like $unit = 10px. This variable can be used repeatedly in your code. Instead of the variable name, as usual, the value (10px) will be substituted.

But what if you need to double the value of a variable? For example, you want to double the bottom margin of an element. Using SASS you can add simple math (+ , - , * , / , %), for example in our case:

$unit = 10px; h1, h2, h3 ( margin-bottom: $unit;) p ( margin-bottom: $unit;) aside ( margin-bottom: $unit*2; /* 20px */) footer( margin-top: $unit* 4; /* 40px */)

Impurities

Impurity can be compared to a block of declarations repeated in the code. This is a piece of code that you can use anywhere in the document. You will not only eliminate unnecessary repetition, but also make the code cleaner, since you will get rid of the need to use the same class for different elements.

For example, you have a separator on your website that you use quite often. For example, you can use it to break up main blocks (for example, articles and header) or even paragraphs. The divider has a bottom padding, a bottom margin, a border, and a shadow.

To create a border, you can add the .shadow-border class to the element. But this will significantly pollute your html and css file.

Shadow-border ( border-bottom: 1px solid #a4a4a4; -webkit-box-shadow: 0px 2px 5px 0px rgba(200, 200, 200, 0.6); box-shadow: 0px 2px 5px 0px rgba(200, 200, 200 , 0.6); padding-bottom: 20px; margin-bottom: 40px; )

If you want correct structure in the css file and clean html markup, you need to add the above rule to the corresponding html elements. It is worth noting that if there are many elements with a delimiter, this will significantly “spoil” the style file, which will make it difficult to maintain the style file.

Header, article, p.intro ( border-bottom: 1px solid #a4a4a4; -webkit-box-shadow: 0px 2px 5px 0px rgba(200, 200, 200, 0.6); box-shadow: 0px 2px 5px 0px rgba(200 , 200, 200, 0.6); padding-bottom: 20px; margin-bottom: 40px; )

Using @mixin, you can define a name for the ad block. This name should not be associated in any way with your HTML.

@mixin shadow-border ( border-bottom: 1px solid #a4a4a4; -webkit-box-shadow: 0px 2px 5px 0px rgba(200, 200, 200, 0.6); box-shadow: 0px 2px 5px 0px rgba(200, 200 , 200, 0.6); padding-bottom: 20px;margin-bottom: 40px;)

Then, to include a mixin in an element, you just need to include the name of the mixin: @include shadow-border;

@mixin shadow-border ( border-bottom: 1px solid #a4a4a4; -webkit-box-shadow: 0px 2px 5px 0px rgba(200, 200, 200, 0.6); box-shadow: 0px 2px 5px 0px rgba(200, 200 , 200, 0.6); padding-bottom: 20px;margin-bottom: 40px;) article ( @include shadow-border;) header ( @include shadow-border;) p.intro ( @include shadow-border;)

Looks good.

Options for Mixins

Parameters for mixins are specified in parentheses following the name of the mixin; The content of the mixin is enclosed in curly braces.

@mixin border-radius($radius: 1px) ( -webkit-border-radius: $radius; -moz-border-radius: $radius; border-radius: $radius; ) /* USE */ .example-class( background-color: #900; @include border-radius(20px); )

Impurity nesting

Sometimes it is very convenient to be able to nest one impurity within another. For example, we need to add a mixin to an already existing mixin:

$border-colour: #a4a4a4; $unit: 10px; @mixin subtle-shadow ( -webkit-box-shadow: 0px 2px 5px 0px rgba(200, 200, 200, 0.6); box-shadow: 0px 2px 5px 0px rgba(200, 200, 200, 0.6); ) @mixin shadow-border ( @include subtle-shadow; border-bottom: $unit/10 solid $border-colour; padding-bottom: $unit*2; margin-bottom: $unit*4;) article ( @include shadow-border ;) header ( @include shadow-border;) p.intro ( @include shadow-border;)

Attachments

Mixins aren't the only thing you can put in CSS selectors (or rather, declaration blocks in a sass file). In SASS you can nest elements inside each other. This will eliminate duplicate selectors and make the code easier to read.

/* regular CSS */ .module h3 ( font-weight: bold;) .module p ( padding-bottom: 10px;)

/* write in SASS */ .module ( h3( font-weight: bold;) p ( padding-bottom: 10px;) )

Attachments and @media queries

Attachments become incredibly useful when working with media queries. Typically, when you work with media queries, you have to create additional styles for different resolutions screen, and sometimes even create a separate style file.

/* viewing window - any, including browsers that do not support @media */ article ( font-size: 14px; line-height: 25px;) article h2 ( font-size: 18px; padding-bottom: 15px;) /* for 300px viewports and wider (mobile first) */ @media only screen and (min-width: 300px) ( article (line-height: 20px;width: 90%;) article h2 (padding-bottom: 10px;) ) / * for 600px viewports and wider */ @media only screen and (min-width: 600px) ( article (line-height: 25px;width: 80%;) article h2 ( padding-bottom: 15px;) ) /* for 900px viewports and wider */ @media only screen and (min-width: 900px) ( article (width: 60%;) ) /* for 1200px viewports and wider */ @media only screen and (min-width: 1200px ) ( article ( font-size: 16px; line-height: 30px; width: 50%;) article h2 ( font-size: 21px; line-height: 35px; padding-bottom: 20px;) )

SASS, on the other hand, allows you to nest all media queries directly inside elements. This will make it easier for you to find and edit styles that affect adaptive layout.

Article ( font-size: 14px; line-height: 25px; h2 ( font-size: 18px; padding-bottom: 15px; ) @media only screen and (min-width: 300px) ( line-height: 20px; width: 90%; h2 ( padding-bottom: 10px; ) ) @media only screen and (min-width: 600px) ( line-height: 25px; width: 80%; h2 ( padding-bottom: 15px;) ) @media only screen and (min-width: 900px) ( width: 60%; ) @media only screen and (min-width: 1200px) ( font-size: 16px; line-height: 30px; width: 50%; h2 ( font- size: 21px; line-height: 35px; padding-bottom: 20px; ) ) )

Importing, @import operator in SASS

@import operator
allows you to include the contents of a third-party CSS(SCSS) file into the current CSS(SCSS) file.
@import is not allowed to be inserted after any declaration other than @charset or another @import .

To include content, for example, _style_two.scss, you need to write like this:

@import "style_two.scss"; /* connect without underscore */

Important: if you connect not a specific file, but a folder, then css files will not be generated for files starting with _ .
For example, having a style.scss file will result in the creation of a style.css , but having a _some.scss file will not. Thus, the underscore means that the file is not a standalone style sheet and can only be imported into another style sheet.

Loops in SASS

The syntax for the loop (each) statement is as follows: $var in . $var is the name of the variable, and list the value of the $var variable.
Instead of $var, values ​​from , then the contents of the cycle are displayed in the style file (by the number of values ).
For example:

SCSS

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

Compiled to:

CSS

.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"); )

@extend operator

There is often a situation where one class needs to have all the styles of another class, in addition to its own styles. The most common solution is to use two classes; the first contains general styles, the second - specific.

The @extend operator avoids these problems by allowing one selector to inherit styles from another selector. For example:

SCSS

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

Compiled to:

CSS

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






2024 gtavrl.ru.