What is Sass and how to use it. Loops in SASS


Sass creates syntactically perfect style sheets ( Syntactically Awesome Style sheets), or at least it is supposed to do so.

When used effectively, Sass helps you specify scalable and concise CSS. At misuse Sass can actually increase file size and add unnecessary or duplicate code.

Below are some helpful tips to help you get the most out of Sass...

1. Structure Sass

Initial definition correct structure site is vital for any new Sass project. Usage partial templates allows you to split CSS into smaller, more manageable blocks of code that are much easier to design and evolve.

Partial template files are created using underscores and are not placed in separate CSS files. Each partial template must be imported using the main Sass file (global.scss), located in the Sass root folder.

Here's an example folder structure that illustrates this principle:

vendor/ base/ | |-- _variables.scss |-- _mixins.scss |-- _placeholders.scss framework/ modules/ global.scss

This folder structure makes it easy for the site to work with it, as well as adding new files. For example, new modules can be easily added to the module folder and then to global.scss using @import .

To demonstrate this, below is an example global.scss file:

/* VENDOR - Reserve and additional files default. ===================================================== ======================== */ @import "vendor/_normalize.scss"; /* BASE - Base Variables file, which also contains the initial Mixins and Fillers. ===================================================== ======================== */ @import "base/_variables.scss"; @import "base/_mixins.scss"; @import "base/_placeholders.scss"; /* FRAMEWORK - File structure. ===================================================== ======================== */ @import "framework/_grid.scss"; @import "framework/_breakpoints.scss"; @import "framework/_layout.scss"; /* MODULES - Reusable site elements. ===================================================== ======================== */ @import "modules/_buttons.scss"; @import "modules/_lists.scss"; @import "modules/_tabs.scss";

2. Use Sass Variables More Efficiently

Variables are one of the most simple elements Sass, but some developers still use them incorrectly from time to time. Developing a site-wide naming convention is essential for working with variables. Without it, they are less understandable and their duplicate use is possible.

Here are some tips for using variables effectively:

  • Give variables meaningful names;
  • Apply and adhere to naming conventions ( Modular, BEM, etc..);
  • Make sure the variable is justified.

Here are some examples of effective use:

$orange: #ffa600; $grey: #f3f3f3; $blue: #82d2e5; $link-primary: $orange; $link-secondary: $blue; $link-tertiary: $grey; $radius-button: 5px; $radius-tab: 5px; But this is ineffective: $link: #ffa600; $listStyle: none; $radius: 5px;

3. Use less impurities

A mixin is a great way to include a section of code multiple times within a site. However, including a mixin is the same as copying and pasting styles into a CSS file. This creates a lot of duplicate code and can lead to a bloated CSS file.

Therefore the mixin should only be used with arguments for quick creation modified styles.
Here's an example:

@mixin rounded-corner($arc) ( -moz-border-radius: $arc; -webkit-border-radius: $arc; border-radius: $arc; )

The rounded-corner mixin can be used in any situation, you just need to change the value of $arc, then it is worth using:

Tab-button ( @include rounded-corner(5px); ) .cta-button ( @include rounded-corner(8px); )

An example of ineffective use of a mixin might look like this:

@mixin cta-button ( padding: 10px; color: #fff; background-color: red; font-size: 14px; width: 150px; margin: 5px 0; text-align: center; display: block; )

This mixin has no arguments and, therefore, it is better to use a placeholder, which brings us closely to point 4.

4. Include placeholders

Unlike mixins, placeholders can be used multiple times without adding any duplicate code. This makes them much more convenient for pure CSS output:

%bg-image ( width: 100%; background-position: center center; background-size: cover; background-repeat: no-repeat; ) .image-one ( @extend %bg-image; background-image:url( /img/image-one.jpg"); ) .image-two ( @extend %bg-image; background-image:url(/img/image-two.jpg"); )

And the compiled CSS:

Image-one, .image-two ( width: 100%; background-position: center center; background-size: cover; background-repeat: no-repeat; ) .image-one ( background-image:url(/img/ image-one.jpg") ; ) .image-two ( background-image:url(/img/image-two.jpg") ; )

Duplicate code in placeholders appears only once and only for unique styles applied to individual selectors. If they are not used, placeholder styles are not output at all.

Considering what was said in point 3, placeholders can be used along with mixins, which will reduce the amount of duplicate code while maintaining the flexibility provided by mixins...

/* FILLER ============================================== */ %btn ( padding: 10px; color:#fff; curser: pointer; border: none; shadow: none; font-size: 14px; width: 150px; margin: 5px 0; text-align: center; display: block; ) /* ADD BUTTON =========================================================== * / @mixin btn-background($btn-background) ( @extend %btn; background-color: $btn-background; &:hover ( background-color: lighten($btn-background,10%); ) ) /* BUTTONS ============================================================ */ .cta -btn ( @include btn-background(green); ) .main-btn ( @include btn-background(orange); ) .info-btn ( @include btn-background(blue); )

5. Use functions to calculate

Functions are used to perform calculations. The Sass function does not output CSS code. Instead, it returns a value that can be used in CSS. This is useful for calculations whose results are applied throughout the site.

For example, functions are useful for calculating the width as a percentage of a particular element:

@function calculate-width ($col-span) ( @return 100% / $col-span ) .span-two ( width: calculate-width(2); // spans 2 columns, width = 50% ) .span- three ( width: calculate-width(3); // spans 3 columns, width = 33.3% )

6. Maintain order and good organization

Place all mixins, functions, placeholders, and variables in their corresponding partial template files. Storing code blocks in separate groups provides the ability to easily edit them and reuse them in the future.

Global items must be stored in the base folder. The base folder should contain global variables such as fonts and color schemes:

$font-primary: "Roboto", sans-serif; $font-secondary: Arial, Helvetica, sans-serif; $color-primary: $orange; $color-secondary: $blue; $color-tertiary: $grey;

Module-specific mixins, functions and variables should be located in the partial template files of the corresponding modules:

$tab-radius: 5px; $tab-color: $grey;

7. Limit the number of investments

Excessive use of nested Sass rules can cause various problems, from too much complexity of the code to over-specificity and bias towards the HTML structure of the page. This can lead to further problems and the need to include !important , which should be avoided if possible.

Here are some golden rules for investing:

  • Never branch a structure more than 3 levels down;
  • Make sure the output CSS is clean and reusable;
  • Use attachment when there is a reason to, not as a default option.

8. Keep things simple

As a final point to this article, I would note that you should try to keep all elements as simple as possible. The goal of Sass is to write cleaner, more manageable CSS code.

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 by reading this article to the 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 in English, 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 English version, this is in order to get used to 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 regular Css code, and Sass eliminates 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, its code structure is based on indentation (after all curly braces it does not) and you should be careful here, since the indentation can be either a tabulator (TAB - 4 spaces) or regular spaces (usually 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; ) ) )

In most code editors (for example, Sublime Text) there is marking of indents 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 in this case there is no need to keep repeating 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, you must specify 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 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 everyone has their 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 along 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...

Translation of the article: The Absolute Beginner's Guide to Sass.
Andrew Chalkley.

What is SASS?

SASS is an abbreviation for Syntactically Awesome Stylesheets is a CSS-based metalanguage whose name can be translated as "CSS with excellent syntax", designed by Hampton Catlin.

It is a means of simplifying the process of creating CSS styles, making it much easier to develop and subsequently maintain code.

Have you, for example, ever, while catering to a certain indecisive client, had to go through the entire contents of a style file in order to find a specific HEX color value in order to replace it with another? Or turn to a calculator application that is not always at hand to calculate the column width for a multi-column template?

SASS has tools at your disposal to relieve you of this routine. These include variables, hagfish, nesting And selector inheritance.

Basically, SASS code is similar to CSS, but the basic distinctive feature The one that is immediately noticeable is the absence of a semicolon after each property-value pair and the absence of curly braces.

Let's take the following piece of CSS code as an example:

#skyscraper_ad
{
display: block;
width: 120px;
height: 600px;
}

#leaderboard_ad
{
display: block;
width: 728px;
height: 90px;
}

Which is equivalent to this SASS:

#skyscraper_ad
display: block
width: 120px
height: 600px

#leaderboard_ad
display: block
width: 728px
height: 90px

SASS uses a spacing (indentation at the beginning of the next line) of two spaces to indicate nesting of code fragments. ( *In the last snippet, for clarity, I highlighted these spaces with a red background.)

Now that we have an idea of ​​how SASS code is created, let's look at the issues that make it so excellent.

Variables.

In SASS, to declare a variable you must precede its name with the dollar symbol $. And if the name of your variable is, say, red , then after the colon we can indicate the following value corresponding to it:

SASS has built-in functions like darken and lighten that can be used to modify the values ​​of these types of variables.

So, in following example The font color in paragraphs will also be red, but darker than that used in h1 headings:

$red: #FF4848
$fontsize: 12px
h1
color: $red

p
color: darken($red, 10%)

You can perform arithmetic operations with variables, such as addition and subtraction, as long as the values ​​used are of the same data type. If, for example, we need to apply more dark shade, then all we need to do is subtract from the color value already used in the code, stored in the variable, a small hexadecimal HEX value equal to, say, #101 . The same applies to the case when it is necessary to change the font size value, say, increase it by 10 pixels; for this we simply add the missing pixels:

p.addition_and_subtraction
color: $red - #101
font-size: $fontsize + 10px

Nesting.

There are two types of nesting in SASS.

Nesting of selectors.

This is the first type of nesting, which is similar to that used to structure HTML code:

$fontsize: 12px

Speaker
.name
font:
weight: bold
size: $fontsize + 10px
.position
font:
size: $fontsize

If you look at the resulting CSS code, any comments will be unnecessary. By nesting the .name class within the .speaker class ( *in the same way - using two spaces at the beginning of the next line) the CSS selector .speaker.name is created. The same applies to the following class name .position , located after the property declaration for the first selector, which results in nesting of the second selector .speaker.position :

Speaker.name(
font-weight: bold;
font-size: 22px; )
.speaker.position (
font-size: 12px; )

Nesting of properties.

The second type of nesting allows you to structure properties with one prefix (* font-family , font-size , font-weight or border-style , border-color , border-radius etc.):

$fontsize: 12px

Speaker
.name
font:
weight: bold
size: $fontsize + 10px
.position
font:
size: $fontsize

In the example above, we use the declaration of the parent, universal property font: and then on a new line after a two-space indentation we indicate the second part of the property, which is usually located after the hyphen.

That is, if we specify the font: property, on next line after two spaces the weight: property, then the result will be equivalent to the familiar font-weight property.

Speaker.name(
font-weight: bold;
font-size: 22px; )
.speaker.position (
font-size: 12px; )

The module provides support for all hyphen-containing properties.

This kind of nesting is a great way to organize and structure your CSS code and avoid unnecessary repetition. ( *DRY- “Don’t Repeat Yourself” - “Don’t repeat yourself.” Situations when CSS formatting certain elements, their styles are repeated and/or redefined elsewhere, making the code difficult to read and maintain).

Hagfish.

Another great feature of SASS is hagfish.

Mixins allow you to reuse entire pieces of SASS code and even pass arguments to them if necessary. And importantly, you can also specify their original values.

To define a mixin, use the specially reserved SASS keyword @mixin followed by the mixin name of your choice. If there is a need for arguments, then list them in parentheses. The default values ​​for the argument are specified when defining the mixin, separated by a colon. ( *In other words, mixins are CSS functions.)

The procedure for using mixins is very simple - after the @include keyword, specify the name of the desired mixin and list the necessary parameters, if any, in parentheses.

Take a look at the following example:

@mixin border-radius($amount: 5px) /* define the mixin */
-moz-border-radius: $amount
-webkit-border-radius: $amount
border-radius: $amount

h1 /* use mixin */
@include border-radius(2px)

Speaker
@include border-radius

This SASS, after compilation, will be converted into the CSS code below:

h1 (
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
border-radius: 2x; )

Speaker (
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px; )

For the h1 header we explicitly specified the border corner radius value, but for the element with the class name .speaker we did not do this, so the default value of 5px was taken.

Selector inheritance.

Another excellent A feature of SASS syntax is the ability of selectors to inherit all styles defined for other selectors. To take advantage of this feature, you must use the @extend keyword, followed by a selector whose properties you want to inherit:

h1
border: 4px solid #ff9aa9

Speaker
@extend h1
border-width: 2px

What will be compiled to:

h1,.speaker (
border: 4px solid #ff9aa9; )

Speaker (
border-width: 2px; )

(*Note that border declaration: 4px solid #ff9aa9; is not repeated within a rule with the .speaker selector, but instead a second selector is added to the first rule. In other words, there is no code duplication.)

Try SASS in action.

Online.

You can get to know SASS online without pre-installation module to your local computer.

But before you start experimenting, at the bottom of the page, select the option "Indented Syntax".

Installed on PC.

SASS itself is an application (gem) of the Ruby platform. Therefore, to install it, you cannot do without first installing the platform itself and the package manager of this programming language RubyGems. After successfully installing the platform itself and the manager, run the following command in the console:

gem install sass

The SASS module can be used as a tool to convert your SASS files into CSS format files in command line mode.

This can be done, for example, by entering the following command:

sass --watch sass_folder:stylesheets_folder

Where sass_folder is the path to the folder containing SASS files (that is, with the .sass extension), and stylesheets_folder is the path to the folder in which the resulting CSS files will be saved after compilation. The --watch command tells the module that it should watch for any changes in the specified folder and, if any, after saving them, convert the original .sass files into equivalent .css files.

Reverse conversion of CSS to SASS.

You can start using SASS by converting the styles used in your existing projects into this format using the "sass-convert" utility.

To do this, in the command line, enter the path to the folder whose contents need to be converted ( *that is, just go to the desired directory in which they are located source files ). Then run the utility mentioned above and provide it with the following parameters:

sass-convert --from css --to sass –R.

Where the -R flag specifies the recursive way to perform the operation. And the next point after it. means that the resulting .sass files will be saved in the current directory. ( *If necessary, instead of a dot, you can specify the path to the folder in which you want to save the resulting files.)

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 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 don't have to worry about 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 command room Ruby string 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).

Before you can use Sass, you need to configure it in your project. If you just want to read, then feel free to read, but we recommend installing Sass first. Install Sass to understand all the features of Sass.

  • Preprocessing

    Writing CSS is fun in itself, but when a stylesheet gets huge, it becomes difficult to maintain. And in this case, the preprocessor will help us. Sass allows you to use features that are not available in CSS itself, for example, variables, nesting, mixins, inheritance and other nice things that return the convenience of writing CSS.

    Once you start using Sass, the preprocessor processes your Sass file and saves it as a simple CSS file that you can use on any site.

    The easiest way to get this result is to use the terminal. Once Sass is installed, you can compile your Sass to CSS using the sass command. You just need to tell Sass where to get the Sass file and what CSS file to compile it into. For example, by running the command sass input.scss output.css in the terminal, you are telling Sass to take one Sass file, input.scss , and compile it into output.css .

  • Variables

    Think of variables as a way to store information that you want to use throughout the writing of each project style. You can store colors, font stacks, or any other CSS values ​​you want to use in variables. To create a variable in Sass you need to use the $ symbol. Let's look at an example:

    SCSS Syntax

    $font-stack : Helvetica , sans-serif ; $primary-color : #333 ; body ( font : 100% $font-stack ; color : $primary-color ; )

    Sass Syntax

    $font-stack : Helvetica , sans-serif $primary-color : #333 body font : 100% $font-stack color : $primary-color

    When Sass is processed, it takes the values ​​we set in $font-stack and $primary-color and inserts them in the regular CSS file in the places where we specified the variables as values. Thus the variables become the most powerful opportunity, for example, when working with brand colors used throughout the site.

    body (font: 100% Helvetica, sans-serif; color: #333; )
  • Nestings

    At writing HTML You may have noticed that it has a clear nested and visual hierarchy. This is not the case with CSS.

    Sass will allow you to nest CSS selectors in the same way as in the HTML visual hierarchy. But remember that excessive nesting makes your document less readable and understandable, which is considered bad practice.

    To understand what we mean, here is a typical example of navigation styles on a website:

    SCSS Syntax

    nav ( ul ( margin : 0 ; padding : 0 ; list-style : none ; ) li ( display : inline-block ; ) a ( display : block ; padding : 6px 12px ; text-decoration : none ; ) )

    Sass Syntax

    nav ul margin : 0 padding : 0 list-style : none li display : inline-block a display : block padding : 6px 12px text-decoration : none

    Did you notice that the ul , li , and a selectors are nested within the nav selector? This is a great way to make your CSS file more readable. When you generate the CSS file, the output will be something like this:

    nav ul ( margin : 0 ; padding : 0 ; list-style : none ; ) nav li ( display : inline-block ; ) nav a ( display : block ; padding : 6px 12px ; text-decoration : none ; )
  • Fragmentation

    You can create Sass file snippets that contain small snippets of CSS that can be used in other Sass files. This is a great way to make your CSS modular and also easier to maintain. A fragment is a simple Sass file whose name begins with an underscore, for example, _partial.scss. Underscore in the Sass file name tells the compiler that it is only a snippet and should not be compiled into CSS. Sass fragments are included using the @import directive.

  • Import

    CSS has an import feature that allows you to split your CSS file into smaller ones and make them easier to maintain. But this method has a significant drawback: every time you use @import in CSS, another HTTP request is created in CSS. Sass takes the idea of ​​importing files via the @import directive, but instead of creating a separate HTTP request, Sass imports the file specified in the directive into the one where it is called, i.e. The output is one CSS file compiled from several fragments.

    For example, you have several Sass file snippets - _reset.scss and base.scss . And we want to import _reset.scss into base.scss .

    SCSS Syntax

    // _reset.scss html, body, ul, ol ( margin: 0; padding: 0; ) // base.scss @import "reset" ; body (font: 100% Helvetica, sans-serif; background-color: #efefef;)

    Sass Syntax

    // _reset.sass html , body , ul , ol margin : 0 padding : 0 // base.sass @import reset body font : 100% Helvetica , sans-serif background-color : #efefef

    Note that we are using @import "reset"; in the base.scss file. When you import a file, you do not need to specify the .scss extension. Sass is a smart language and it will figure itself out. When the CSS is generated you will get:

    html , body , ul , ol ( margin : 0 ; padding : 0 ; ) body ( font : 100% Helvetica , sans-serif ; background-color : #efefef ; )
  • Mixins (mixins)

    Some things in CSS are quite tedious to write, especially in CSS3, where on top of that you often need to use a large number of vendor prefixes. Mixins allow you to create groups of CSS declarations that you will use multiple times throughout your site. It's good to use mixins for vendor prefixes. Example for border-radius:

    SCSS Syntax

    @mixin border-radius ($radius) ( -webkit-border-radius : $radius ; -moz-border-radius : $radius ; -ms-border-radius : $radius ; border-radius : $radius ; ) .box ( @include border-radius (10px); )

    Sass Syntax

    =border-radius ($radius ) -webkit-border-radius : $radius -moz-border-radius : $radius -ms-border-radius : $radius border-radius : $radius .box +border-radius (10px )

    To create a mixin, use the @mixin directive + the name of the mixin. We named our mixin border-radius. Also, in the mixin we use the $radius variable inside the parentheses, thereby allowing us to pass whatever we want in the variable. Once you have created a mixin, you can use it as CSS parameter, starting the call with @include and the name of the mixin. When your CSS compiles you will get this:

    .box ( -webkit-border-radius : 10px ; -moz-border-radius : 10px ; -ms-border-radius : 10px ; border-radius : 10px ; )
  • Extension/Inheritance

    This is one of the most useful functions Sass. Using the @extend directive, you can inherit sets of CSS properties from one selector to another. This allows you to keep your Sass file "clean". In our example, we'll show you how to style error, warning, and success notifications using other Sass features that go hand-in-hand with the extension's template classes.

    A template class is a special type of class that is only output when using an extension - this will save your compiled CSS clean and neat.

    SCSS Syntax

    %equal-heights ( display : flex ; flex-wrap : wrap ; ) %message-shared ( border : 1px solid #ccc ; padding : 10px ; color : #333 ; ) .message ( @extend %message-shared ; ) . success ( @extend %message-shared ; border-color : green ; ) .error ( @extend %message-shared ; border-color : red ; ) .warning ( @extend %message-shared ; border-color : yellow ; )

    Sass Syntax

    // This piece of code won't make it into the CSS because %equal-heights was never expanded.%equal-heights display : flex flex-wrap : wrap // This piece of code will end up in CSS because %message-shared is extended.%message-shared border : 1px solid #ccc padding : 10px color : #333 .message @extend %message-shared .success @extend %message-shared border-color : green .error @extend %message-shared border-color : red .warning @extend %message-shared border-color : yellow

    The above code tells the .message , .success , .error , and .warning classes to behave like %message-shared . This means that wherever %message-shared is called, .message , .success , .error and .warning will also be called. The magic happens in the generated CSS, where each of these classes receives CSS properties, just like %message-shared . This will allow you to avoid writing many classes in HTML elements.

    You can expand most simple CSS selectors adding to template classes in Sass, however, using templates is the simplest way be sure that you don't extend the class wherever it is used in your styles, which could lead to unintended style sets in your CSS.

    When you generate your CSS, it will look like the example below. Please note that %equal-heights does not make it into the CSS because it has never been used.

    .message, .success, .error, .warning (border: 1px solid #cccccc; padding: 10px; color: #333;).success (border-color: green;).error (border-color: red;). warning ( border-color : yellow ; )
  • Mathematical operators

    Using math in CSS is very useful. Sass has several standard math operators such as + , - , * , / and % . In our example, we're doing some simple math to calculate the width of aside and article .

    SCSS Syntax

    .container ( width : 100% ; ) article [ role = "main" ] ( float : left ; width : 600px / 960px * 100% ; ) aside [ role = "complementary" ] ( float : right ; width : 300px / 960px * 100% ; )

    Sass Syntax

    .container width : 100% article [ role = "main" ] float : left width : 600px / 960px * 100% aside [ role = "complementary" ] float : right width : 300px / 960px * 100%

    We created a simple responsive modular grid with a width of 960 pixels. Using mathematical operators, we took the resulting data with pixel values ​​and converted them to percentages without much effort. The compiled CSS looks like this:

    .container ( width : 100% ; ) article [ role = "main" ] ( float : left ; width : 62.5% ; ) aside [ role = "complementary" ] ( float : right ; width : 31.25% ; )






2024 gtavrl.ru.