Sass for little ones - a detailed guide. Nested selectors and properties


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

At effective use Sass helps you define scalable and concise CSS. At misuse Sass can actually increase file size and add unnecessary or duplicate code.

Below is a series useful tips that will 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 develop and evolve.

Partial template files are created using symbols underscore and are not put into 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 provides simple work site 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 effective application variables:

  • 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

An impurity is great way 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 specific 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 may 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.

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. The underscore in a 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've created a mixin, you can use it as a CSS parameter by 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 you use an extension - this will keep your compiled CSS clean and tidy.

    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 to ensure that you don't extend a 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% ; )

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 to a 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 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

For the 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, its code structure is based on indentation (after all curly braces not in it) 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, then you will have to specify all the colors of the buttons 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 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 of the main file you have. 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 values ​​created after 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 the name of the mixin, separated by a space, and 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...

What is Sass, why is it needed, its capabilities, installation and how to use it in your projects

What is Sass

Sass(Syntactically Awesome Stylesheets) is one of the most advanced, stable and feature-rich preprocessors. It is very popular among developers. Sass is more advanced version of CSS that has much more features, and Sass is designed for simplification cascading style sheets.

Sass syntax has 2 types: SASS And SCSS. SCSS is more similar to CSS, while SASS is distinguished by the absence of curly braces. Nested elements are implemented using indentation. This is the syntax we will use here.

Why do you need Sass?

To understand why Sass is needed, let's list some of it: possibilities:

  1. Sass allows nesting CSS rules into each other
  2. Property nesting
  3. Using Variables
  4. Arithmetic support
  5. Operations with flowers
  6. Ability to import a sass file sass, scss And css files
  7. Using Mixins
  8. And much more

In short, why do you need Sass: it accelerates And simplifies development process.

How to use Sass

Exist different ways start using Sass:

  1. Using applications (Koala, CodeKit, Compass and others)
  2. With the help command line
  3. Using task managers
  4. Easily convert Sass to CSS using online services

Consider using Sass for task manager Gulp. Before you begin the installation, it is advisable to familiarize yourself with the basics of Gulp.

Installing and connecting gulp-sass

To install the plugin gulp-sass to our project, open the command line in the project folder. Let's introduce next command:

npm i gulp - sass -- save - dev

The plugin will be installed in the node_modules folder and a corresponding entry will be added to the package.json file. After successful installation we need to plug our package in file gulpfile.js.

var gulp = require("gulp"); sass = require("gulp-sass");

Now let's create a task sass.

gulp. task ("sass" , function ()( return gulp . src ( "app/sass/main.sass" ) . pipe ( sass (). on ( "error" , sass . logError )) . pipe ( gulp . dest ( "app/css" )); ));

gulp.src- What do we take for processing?

.pipe(sass())- Convert Sass to CSS

sass()- in brackets you can specify additional settings display CSS at the exit.
For example, sass((outputStyle: " expanded")) - fully expanded CSS.
Other meanings: nested(default), compact- each selector is on a different line, compressed- all in one line.

If we suddenly make a mistake, we can display a message on the screen where it is located. To do this, let's add .on("error", sass.logError).

Let's execute our created task gulp-sass. On the command line we enter gulp sass.

Gulp automatically converted SASS to CSS and created the file main.css.

If you need to select not one file, but several, you can select all files at once. To do this, let’s change a little the line where we select the sass files for conversion:

gulp. src("app/sass/**/*.sass")

sass/**/*.sass- means selecting all files (with extension .sass) in all folders of the sass folder.

To summarize: connected the plugin gulp-sass, created a task sass and added error output (if one occurs). Now you can do the default task. Those. our tax gulp-sass will be launched with the command gulp.

gulp. task("default" , ["sass" ]);

We get the following gulpfile.js

var gulp = require("gulp"); var sass = require("gulp-sass"); gulp. task ("sass" , function ()( return gulp . src ( "app/sass/**/*.sass" ) . pipe ( sass (). on ( "error" , sass . logError )) . pipe ( gulp . dest ("app/css")) )); gulp. task("default" , ["sass" ]);

Let's look at some of the features of Sass using examples.

Their great amount, let's consider only the most popular ones. WITH full list can be found on the official website.

Nesting of rules

Property nesting

Using $variables

Arithmetic operations with numbers

Arithmetic operations with colors

If you're a new WordPress theme designer, you've probably already encountered the problem of long CSS files while keeping them structured, scalable, and readable. You've also probably heard that many designers and front-end developers recommend using a CSS preprocessor language such as Sass or LESS. But what is it? how to start working with them? In this article, we'll show you how to get started with Sass. We will also tell you what a CSS preprocessor is, why it is needed and how to install it and use it correctly.

What is Sass?

The CSS we use was designed to create style sheets for websites. however, as the web and the needs of designers evolved, a style sheet language was needed that would allow us to do more with less effort and time. CSS preprocessor languages ​​like Sass allow us to use features that are not currently available in CSS, such as using variables, basic math operators, nested rules, mixins, etc.

It is similar in many ways to PHP language, which is a preprocessor that executes scripts on the server and generates HTML as output. Sass also processes .scss files to generate CSS files that can be used by browsers.

Since version 3.8, style sheets WordPress admin have been ported to use Sass for development. There are many WordPress store themes that successfully use Sass to speed up the development process.

Using Sass to Develop WordPress Themes

Most theme developers use local hosting for work before releasing the theme to a live site. Since Sass is a preprocessor language, you need to install it on your localhost.

First, you need to install Sass. It can be used as a command line, but there are also several GUI applications for Sass. We recommend using Koala because it is free, open source, and available for Mac, Windows, and Linux.

To test this example you will need to create new topic. Just create new folder V /wp-content/themes/. You can call it anything you like, for example 'mytheme'. Inside this empty folder, create another folder and call it stylesheets.

In the stylesheets folder, create a file style.scss using any text editor like Notepad.

Now you need to open Koala and click on the plus icon to add a new project. Next, select your theme folder and add it to your project. You will notice that Koala will automatically find the Sass file in your stylesheets folder and display it.

Click right click mouse on your Sass file and select the option Set Output Path. Next select the root folder of your theme, from our example it will be /wp-content/themes/mytheme/ and press Enter. Koala will generate a CSS file as output, in your theme folder. To test it, you need to open your Sass file − style.scss- V text editor type Notepad and add the following code to it:

$fonts: arial, verdana, sans-serif; body ( font-family:$fonts; )

Now save your changes and return to Koala. Right-click on your Sass file and a sidebar will appear on the right. To compile your Sass file, simply click on the button 'Compile'. You can see the result by opening the file style.css in your theme folder and the result will be:

Body (font-family: arial, verdana, sans-serif; )

Notice that we have defined a variable $fonts in our Sass file. Now, in any place where we need to add a font family, we will not need to register all the fonts again and again. We can just use $fonts.

What benefits does Sass bring to CSS?

Sass is incredibly powerful and has backwards compatible, and extremely easy to learn. As we mentioned earlier, you can create variables, nested rules, mixins, use imports, math and logical operators etc. Now we will show you some examples and you can try them on your WordPress theme.

Managing multiple style sheets

One of the most big problems What you'll encounter as a WordPress theme designer are large style sheets with a lot of sections. You'll likely scroll up and down the file many times to change properties as you work on the theme. Using Sass, you can import multiple files into your main stylesheet and end up with a single CSS file for your theme.

What about CSS @import?

The problem with using @import in your CSS file is that every time you add @import, your CSS file does additional HTTP request to the server. This affects the loading of the page, which is not particularly good for the project. On the other hand, when you use @import in Sass, it will include the files in your Sass file and combine them into a single CSS file for all browsers.

In order to understand how to use @import in Sass, you first need to create a file reset.scss in your theme's stylesheets folder and paste the following code into it.

/* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 License: none (public domain) */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video ( margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline ; ) /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section ( display: block; ) body ( line-height: 1; ) ol, ul ( list-style: none; ) blockquote, q ( quotes: none; ) blockquote:before, blockquote:after, q:before, q:after ( content: ""; content: none; ) table ( border- collapse: collapse; border-spacing: 0; )

Now open your main style.scss file and add the following line to where you want to import the reset file.







2024 gtavrl.ru.