Как компилировать все файлы sass в один CSS?
И есть один main.sass файл который компилируется в main.css. Создал еще пару sass файлов что бы разделить код на блоки и через @import ставлю в main.sass, но по мимо него создаются еще и другие css файлы. 1 sass файл = 1 css файл
- Вопрос задан более трёх лет назад
- 2129 просмотров
Комментировать
Решения вопроса 0
Ответы на вопрос 2
Алексей Уколов @alexey-m-ukolov
Создал еще пару sass файлов что бы разделить код на блоки
В названии этих файлов в начале должен быть _ . Например, _foo.scss .
If you have a SCSS or Sass file that you want to import but don’t want to compile to a CSS file, you can add an underscore to the beginning of the filename. This will tell Sass not to compile it to a normal CSS file. You can then import these files without using the underscore.
For example, you might have _colors.scss. Then no _colors.css file would be created, and you can do
@import «colors»;
and _colors.scss would be imported.
Ответ написан более трёх лет назад
Комментировать
Нравится 1 Комментировать
frontend-разработчик
достаточно во второй строке таски сообщить gulp’у, что он должен забирать не все файлы отовсюду, а один корневой main.sass , в который подключаются остальные
return gulp.src(‘app/sass/path/to/main.sass’)
Ответ написан более трёх лет назад
Комментировать
Нравится Комментировать
Ваш ответ на вопрос
Войдите, чтобы написать ответ

- Sass
Как правильно переписать css в scss с нестингом?
- 1 подписчик
- 15 нояб.
- 31 просмотр

- Webpack
- +1 ещё
Как правильно настроить загрузчик sass в webpack?
- 1 подписчик
- 15 нояб.
- 35 просмотров
How to Use Sass with CSS

Adalbert Pungu

Hi there! If you are reading this article, you’re probably trying to understand what Sass is and how it works.
Sass is a CSS preprocessor that helps you manage tasks in large projects where the style sheets get larger, you have a number of lines of CSS code, and it becomes difficult to maintain your CSS codes.
This is where Sass becomes useful, as it has features that don’t yet exist in CSS like nesting, creating functions with mixins, inheritance, and more. These features will help you write maintainable CSS code.
Sass lets you reuse your code, split it into files, and it also helps you create functions, variables, nest your CSS selectors, and other shortcuts.
How Sass Works
The web browser does not understand Sass code, though – it only understands CSS code. This means that you have to transform the Sass code into CSS code.
To do this, the compiler will generate a file with the CSS code. This transformation is called compilation. When you write Sass code in a .scss file, it is compiled into a regular CSS file that the browser will use to display it on the web page.
Why Use Sass?
There are many advantages to using Sass, so let’s look at some of them now:
First, Sass is easy to understand if you know CSS. Since it’s a CSS preprocessor its syntax is similar.
Also, if you use Sass, your CSS code will be compatible with all versions of browsers.
Sass also makes it possible to reuse your code by creating variables and functions with mixins (cutting up pieces of code) that can be reused over and over again. This helps you save time and allows you to code faster.
Speaking of saving time, Sass reduces the repetition of writing CSS code. This is thanks to its features like functions, variables, inheritance, and so on.
Finally, Sass is compiled to CSS and adds all the necessary vendor prefixes so you don’t have to worry about writing them manually.
How to Install and Configure Sass
In this article, I’ll show you two ways to install Sass.
How to Install Sass with Node.js
First, we’ll download and install Node. Then we’ll use the JavaScript package manager npm to install Sass and configure it in your project.
We are going to do a global installation, because this will save you from installing it every time you plan to work in your projects with Sass.
Here are the steps to follow to install and set up Sass in a project:
First, open your terminal and type:
npm install -g scss
Again, this is global installation. If you do this, you avoid installing it every time you plan to work with Sass in your projects.
Then, in the project folder, create a Sass file in the one you are going to work on:
style.scss
style is the file name and .scss is the Sass extension name.
Then you will use the following command to generate a style.css file from the SASS file:
sass --watch style.scss style.css
style.scss is the source file and style.css is the destination file where Sass generates the CSS code.
Now installation and configuration are complete! You can use Sass in your projects.
But before we get into how to use Sass, I want to show you a second way of doing it. I recommend this way, as it is the simplest and easiest way to install and configure Sass.
How to Install Sass Using VS Code
First, download and install Microsoft’s VS Code editor if you haven’t already. Then launch the editor so you can download the Live Sass Compiler extension.

And that’s all you have to do. Once the installation is done, you’ll be able to use Sass in your projects. Easy, right?
How to Use Sass in a Project
To understand how to use Sass, we will work on an example project where we will create two grids. The idea here is not to learn everything about Sass but what you see is mostly what you need to know to start using Sass.
Here is an overview of what we will create to understand Sass.

You might be wondering why I took the grid example? Well, because we often use grids in web pages and they’re simple to understand.
First of all, you should know that we’ll do all the coding in the Sass file (style.scss) and not in the style.css file. It is Sass that will generate a CSS file for us with the same code.
To start, create a folder with two folders inside, CSS and images. Then inside the CSS folder create a file with the Sass extension – in my case it’s style.scss.
Then open it and the file will be detected right away. Below the editor a button will appear named Watch Sass. Just click on it to tell Sass to watch this file and start generating (compiling) code in the CSS file.


Once SASS finishes compiling it will create three files in the project’s CSS folder: style.css, style.scss, and style.css.map. It tracks all the changes and it is ready to generate CSS code.
If you come back soon to continue working, all you have to do is open the file which has the extension .scss. Then click on Watch Sass for Sass to start generating the modifications in the CSS file (otherwise nothing will be generated in the CSS file).
I hope it’s going ok so far. You have just seen how to install, configure, and start using Sass in your project. So now let’s continue with our example of the grids to understand the different functionalities Sass brings.
How to Use Variables in Sass
Before seeing how to create Sass variables, create an index.html file copy and paste the code below in the file:
card with sass
Lorem
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum porro dolores sapiente.
Lorem
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque amet obcaecati nihil.
Run the file in your browser to see the result.

Sass lets you create variables, but I want to show you a difference between Sass and CSS.
body
If you look at this example, it’s CSS. But if in the project I want to reuse any color, padding, or font, I have to rewrite the same code (in CSS).
But with Sass I can create variables so I can reuse these features. To create a variable in Sass, we use the dollar sign $ followed by the variable name and a colon for the value. Keep in mind that it’s best to create a name that reflects the object you’re going to use.
/* Creating and Using Variables */ $fonts: 'Poppins', Helvertica, sans-serif; $primary-color: #ab99ca; $spacing: 2rem; body
Add the above code in the style.scss file. Since we are working with a Sass file and HTML does not recognize Sass, to see the results we’ll specify the CSS file that has been generated in our file index.html.
How to Link the CSS File
It’s really important to link the CSS file to index.html, to allow the CSS file to apply the CSS styles to the HTML. Otherwise there will be no styling applied and you will only see the code produced by the HTML.
So we will link our CSS file in the index.html file. In my case:

Run the file in your browser to see the result.

We will now see how to organize the code thanks to IMPORTS. The code will be cut into files while we keep using our example.
When creating a file, the file name will be followed by an underscore(_) at the beginning to prevent it from being compiled by Sass.
Create three files:

- _variables.scss : to add the variables
- _mixins.scss : to add the functions that we will reuse
- _card.scss : to add the styles of our cards
Copy and paste the variables you created in the style.scss file and put them in the _variables.scss file:
$fonts: 'Poppins', Helvetica, sans-serif; $primary-color: #ab99ca; $spacing: 2rem; $dark-grey: #999;
For the _mixins.scss file, this is where we’ll create the reusable functions with mixins.
Mixins allow you to create reusable functions. To declare a function you must enter @mixin name_fonction < content >or if your function has a parameter, you must enter @mixin name_fonction($name_variable) < content >.
To use mixins, you have to import it by typing @include namefunction(); which saves time in a large project.
Add this code to the _mixins.scss file:
@mixin flex-center < display: flex; align-items: center; justify-content: center; >/* $radius is the parameter of the function */ @mixin border-radius($radius)
For the _card.scss file, add this code to it:
.card < background-color: white; width: 20rem; overflow: hidden; margin: 2rem; box-shadow: 5px 5px 5px 5px #000; @include border-radius(0.5rem); /* using the mixins function */ img < height: 15rem; background-size: cover; background-position: center center; >.card_content < padding: $spacing; >.card_title < margin: 0; color: black; >.card_description < margin: 0; color: $dark-grey; >&_dark < background-color: black; .card_title < color: white; >> >
In the code above we’re using nesting and aliases. Nesting helps us simplify the way we write our CSS styles and allows us to nest CSS selectors.
For aliases you can use (&) or (and) followed by the class name that will resume the parent selector’s code.
To use an alias, you must import it by typing the alias followed by the name of the variable (&_dark).
If you try to run the index.html file, nothing will change. It does not change because we have created files that are not related to index.html and our style.sass file only generates the code it has.
To fix this, we’ll import all the files we’ve created into the style.sass file so that when SASS does the monitoring, it’ll generate the code of those files.
/* file import */ @import 'variables'; @import 'mixins'; @import 'card';
For the style.scss file, add the above code. The style.scss file should be like this:
/* file import */ @import 'variables'; @import 'mixins'; @import 'card'; body < font-family: $fonts; /* variable usage */ background-color: $primary-color; padding: $spacing; min-height: 100vh; @include flex-center(); /* using the mixins function */ >
In the previous code, I imported the files (SASS import) into style.css so that they can be tracked and generate code when there are changes.
Run the index.html file in your browser to see the result.

If you get the same result as in the capture above, congratulations, you now understand how Sass works.
Here is the preview link for the project we built: https://adalbertpungu.github.io/card_with_sass/
And here’s the GitHub repository link:
Conclusion
In this article, you learned how Sass works by building a simple photo grid. In this small project, we’ve covered many core Sass features, but not all of them. So I hope you will start using it in your projects to learn more.
You can check the documentation if you want to dive deeper: https://sass-lang.com/documentation.
That’s all for this article. Thank you for reading! I think you’re ready to try using Sass.
Follow me on Twitter: twitter.com/AdalbertPungu
Основы Sass
Прежде, чем Вы сможете использовать Sass, Вам необходимо его настроить в вашем проекте. Если Вы хотите просто почитать, то не стесняйтесь — читайте, но мы рекомендуем сначала установить Sass. Установите Sass для того, чтобы разобраться во всех возможностях Sass.
Препроцессинг
Написание CSS само по себе весело, но когда таблица стилей становится огромной, то становится и сложно её обслуживать. И вот в таком случае нам поможет препроцессор. Sass позволяет использовать функции недоступные в самом CSS , например, переменные, вложенности, миксины, наследование и другие приятные вещи, возвращающие удобство написания CSS.
Как только Вы начинаете пользоваться Sass, препроцессор обрабатывает ваш Sass-файл и сохраняет его как простой CSS -файл, который Вы сможете использовать на любом сайте.
Самый простой способ получить такой результат — использовать терминал. После того, как Sass установлен, вы можете компилировать ваш Sass в CSS , используя команду sass . Вам всего лишь нужно сообщить Sass, где взять файл Sass и в какой файл CSS его скомпилировать. Например, запустив команду sass input.scss output.css в терминале, вы сообщаете Sass взять один Sass файл, input.scss , и скомпилировать в файл output.css .
Также, вы можете следить за изменениями только определенных файлов или папок, используя флаг —watch . Данный флаг сообщает Sass, что необходимо следить за изменениями указанных файлов и при наличии таковых производить перекомпиляцию CSS после сохранения файлов. Если вы хотите отслеживать изменения (вместо ручной перекомпиляции) вашего файла, например, input.scss , то вам необходимо просто добавить флаг в команду:
sass –watch input.scss output.css
Вы также можете указать папки для отслеживания изменений и куда сохранять компилированные CSS файлы, для этого достаточно указать пути и разделить их двоеточием, например:
sass --watch app/sass:public/stylesheets
Sass будет отслеживать все файлы в директории app/sass и компилировать CSS в директорию public/stylesheets .
Переменные
Думайте о переменных, как о способе хранения информации, которую вы хотите использовать на протяжении написания всех стилей проекта. Вы можете хранить в переменных цвета, стеки шрифтов или любые другие значения CSS , которые вы хотите использовать. Чтобы создать переменную в Sass нужно использовать символ $ . Рассмотрим пример:
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
CSS Output
body font: 100% Helvetica, sans-serif; color: #333; >
Когда Sass обрабатывается, он принимает значения, заданные нами в $font-stack и $primary-color и вставляет их в обычном CSS -файле в тех местах, где мы указывали переменные как значения. Таким образом переменные становятся мощнейшей возможностью, например, при работе с фирменными цветами, используемыми на всем сайте.
Вложенности
При написании HTML , Вы, наверное, заметили, что он имеет четкую вложенную и визуальную иерархию. С CSS это не так.
Sass позволит вам вкладывать CSS селекторы таким же образом, как и в визуальной иерархии HTML. Но помните, что чрезмерное количество вложенностей делает ваш документ менее читабельным и воспринимаемым, что считается плохой практикой.
Чтобы понять что мы имеем ввиду, приведем типичный пример стилей навигации на сайте:
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
CSS Output
nav ul margin: 0; padding: 0; list-style: none; > nav li display: inline-block; > nav a display: block; padding: 6px 12px; text-decoration: none; >
Вы заметили, что селекторы ul , li , и a являются вложенными в селектор nav ? Это отличный способ сделать ваш CSS -файл более читабельным. Когда вы сгенерируете CSS -файл, то на выходе вы получите что-то вроде этого:
Фрагментирование
Вы можете создавать фрагменты Sass-файла, которые будут содержать в себе небольшие отрывки CSS , которые можно будет использовать в других Sass-файлах. Это отличный способ сделать ваш CSS модульным, а также облегчить его обслуживание. Фрагмент — это простой Sass-файл, имя которого начинается с нижнего подчеркивания, например, _partial.scss . Нижнее подчеркивание в имени Sass-файла говорит компилятору о том, что это только фрагмент и он не должен компилироваться в CSS. Фрагменты Sass подключаются при помощи директивы @import .
Импорт
CSS имеет возможность импорта, которая позволяет разделить ваш CSS -файл на более мелкие и облегчить @import , то в CSS создается еще один HTTP -запрос. Sass берет идею импорта файлов через директиву @import , но вместо создания отдельного HTTP -запроса Sass импортирует указанный в директиве файл в тот, где он вызывается, т.е. на выходе получается один CSS -файл, скомпилированный из нескольких фрагментов.
Например, у вас есть несколько фрагментов Sass-файлов — _reset.scss и base.scss . И мы хотим импортировать _reset.scss в 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
CSS Output
html, body, ul, ol margin: 0; padding: 0; > body font: 100% Helvetica, sans-serif; background-color: #efefef; >
Обратите внимание на то, что мы используем @import ‘reset’; в base.scss файле. Когда вы импортируете файл, то не нужно указывать расширение .scss . Sass — умный язык и он сам догадается.
Миксины (примеси)
Некоторые вещи в CSS весьма утомительно писать, особенно в CSS3 , где плюс ко всему зачастую требуется использовать большое количество вендорных префиксов. Миксины позволяют создавать группы деклараций CSS , которые вам придется использовать по нескольку раз на сайте. Вы даже можете передавать переменные в миксины, чтобы сделать их более гибкими. Так же хорошо использовать миксины для вендорных префиксов. Пример для transform :
SCSS Syntax
@mixin transform($property) -webkit-transform: $property; -ms-transform: $property; transform: $property; > .box @include transform(rotate(30deg)); >
Sass Syntax
=transform($property) -webkit-transform: $property -ms-transform: $property transform: $property .box +transform(rotate(30deg))
CSS Output
.box -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); >
To create a mixin you use the @mixin directive and give it a name. We’ve named our mixin transform . We’re also using the variable $property inside the parentheses so we can pass in a transform of whatever we want. After you create your mixin, you can then use it as a CSS declaration starting with @include followed by the name of the mixin.
Расширение/Наследование
Это одна из самых полезных функций Sass. Используя директиву @extend можно наследовать наборы свойств CSS от одного селектора другому. Это позволяет держать ваш Sass-файл в «чистоте». В нашем примере мы покажем вам как сделать стили оповещений об ошибках, предупреждениях и удачных исходах, используя другие возможности Sass, которые идут рука-об-руку с расширением, классами-шаблонами. Класс-шаблон — особый тип классов, который выводится только при использовании расширения — это позволит сохранить ваш скомпилированный CSS чистым и аккуратным.
SCSS Syntax
/* This CSS will print because %message-shared is extended. */ %message-shared border: 1px solid #ccc; padding: 10px; color: #333; > // This CSS won't print because %equal-heights is never extended. %equal-heights display: flex; flex-wrap: wrap; > .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 CSS will print because %message-shared is extended. */ %message-shared border: 1px solid #ccc padding: 10px color: #333 // This CSS won't print because %equal-heights is never extended. %equal-heights display: flex flex-wrap: wrap .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
CSS Output
.message, .success, .error, .warning border: 1px solid #ccc; padding: 10px; color: #333; > .success border-color: green; > .error border-color: red; > .warning border-color: yellow; >
Вышеуказанный код сообщает классам .message , .success , .error и .warning вести себя как %message-shared . Это означает, что где бы не вызывался %message-shared , то и .message , .success , .error и .warning тоже будут вызваны. Магия происходит в сгенерированном CSS , где каждый из этих классов получает css-свойства, как и %message-shared . Это позволит вам избежать написания множества классов в HTML элементах.
Вы можете расширить большинство простых CSS селекторов прибавление к классам-шаблонам в Sass, однако, использование шаблонов — простейший способ быть уверенным, что вы не расширяете класс везде, где он используется в ваших стилях, что могло бы привести к непреднамеренным наборам стилей в вашем CSS.
Когда вы генерируете ваш CSS , то он будет выглядеть как пример ниже. Обратите внимание, %equal-heights не попадает в CSS , так как ни разу не был использован.
Математические операторы
Использовать математику в CSS очень полезно. Sass имеет несколько стандартных математических операторов, таких как + , — , * , / и % . В нашем примере мы совершаем простые математические вычисления для расчета ширины aside и 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%
CSS Output
.container width: 100%; > article[role="main"] float: left; width: 62.5%; > aside[role="complementary"] float: right; width: 31.25%; >
Мы создали простую адаптивную модульную сетку, с шириной в 960 пикселей. Используя математические операторы, мы использовали полученные данные с пиксельными значениями и конвертировали их в процентные, причем без особых усилий. Скомпилированный CSS выглядит так:
Sass © 2006–2018 Hampton Catlin, Natalie Weizenbaum, Chris Eppstein, Jina Anne, и многочисленные участники. Доступно для использования и изменения по лицензии MIT.
Основы Sass
Прежде, чем Вы сможете использовать Sass, Вам необходимо его настроить в вашем проекте. Если Вы хотите просто почитать, то не стесняйтесь — читайте, но мы рекомендуем сначала установить Sass. Установите Sass для того, чтобы разобраться во всех возможностях Sass.
Препроцессинг
Написание CSS само по себе весело, но когда таблица стилей становится огромной, то становится и сложно её обслуживать. И вот в таком случае нам поможет препроцессор. Sass позволяет использовать функции недоступные в самом CSS , например, переменные, вложенности, миксины, наследование и другие приятные вещи, возвращающие удобство написания CSS.
Как только Вы начинаете пользоваться Sass, препроцессор обрабатывает ваш Sass-файл и сохраняет его как простой CSS -файл, который Вы сможете использовать на любом сайте.
Самый простой способ получить такой результат — использовать терминал. После того, как Sass установлен, вы можете компилировать ваш Sass в CSS , используя команду sass . Вам всего лишь нужно сообщить Sass, где взять файл Sass и в какой файл CSS его скомпилировать. Например, запустив команду sass input.scss output.css в терминале, вы сообщаете Sass взять один Sass файл, input.scss , и скомпилировать в файл output.css .
Также, вы можете следить за изменениями только определенных файлов или папок, используя флаг —watch . Данный флаг сообщает Sass, что необходимо следить за изменениями указанных файлов и при наличии таковых производить перекомпиляцию CSS после сохранения файлов. Если вы хотите отслеживать изменения (вместо ручной перекомпиляции) вашего файла, например, input.scss , то вам необходимо просто добавить флаг в команду:
sass –watch input.scss output.css
Вы также можете указать папки для отслеживания изменений и куда сохранять компилированные CSS файлы, для этого достаточно указать пути и разделить их двоеточием, например:
sass --watch app/sass:public/stylesheets
Sass будет отслеживать все файлы в директории app/sass и компилировать CSS в директорию public/stylesheets .
Переменные
Думайте о переменных, как о способе хранения информации, которую вы хотите использовать на протяжении написания всех стилей проекта. Вы можете хранить в переменных цвета, стеки шрифтов или любые другие значения CSS , которые вы хотите использовать. Чтобы создать переменную в Sass нужно использовать символ $ . Рассмотрим пример:
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
CSS Output
body font: 100% Helvetica, sans-serif; color: #333; >
Когда Sass обрабатывается, он принимает значения, заданные нами в $font-stack и $primary-color и вставляет их в обычном CSS -файле в тех местах, где мы указывали переменные как значения. Таким образом переменные становятся мощнейшей возможностью, например, при работе с фирменными цветами, используемыми на всем сайте.
Вложенности
При написании HTML , Вы, наверное, заметили, что он имеет четкую вложенную и визуальную иерархию. С CSS это не так.
Sass позволит вам вкладывать CSS селекторы таким же образом, как и в визуальной иерархии HTML. Но помните, что чрезмерное количество вложенностей делает ваш документ менее читабельным и воспринимаемым, что считается плохой практикой.
Чтобы понять что мы имеем ввиду, приведем типичный пример стилей навигации на сайте:
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
CSS Output
nav ul margin: 0; padding: 0; list-style: none; > nav li display: inline-block; > nav a display: block; padding: 6px 12px; text-decoration: none; >
Вы заметили, что селекторы ul , li , и a являются вложенными в селектор nav ? Это отличный способ сделать ваш CSS -файл более читабельным. Когда вы сгенерируете CSS -файл, то на выходе вы получите что-то вроде этого:
Фрагментирование
Вы можете создавать фрагменты Sass-файла, которые будут содержать в себе небольшие отрывки CSS , которые можно будет использовать в других Sass-файлах. Это отличный способ сделать ваш CSS модульным, а также облегчить его обслуживание. Фрагмент — это простой Sass-файл, имя которого начинается с нижнего подчеркивания, например, _partial.scss . Нижнее подчеркивание в имени Sass-файла говорит компилятору о том, что это только фрагмент и он не должен компилироваться в CSS. Фрагменты Sass подключаются при помощи директивы @import .
Импорт
CSS имеет возможность импорта, которая позволяет разделить ваш CSS -файл на более мелкие и облегчить @import , то в CSS создается еще один HTTP -запрос. Sass берет идею импорта файлов через директиву @import , но вместо создания отдельного HTTP -запроса Sass импортирует указанный в директиве файл в тот, где он вызывается, т.е. на выходе получается один CSS -файл, скомпилированный из нескольких фрагментов.
Например, у вас есть несколько фрагментов Sass-файлов — _reset.scss и base.scss . И мы хотим импортировать _reset.scss в 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
CSS Output
html, body, ul, ol margin: 0; padding: 0; > body font: 100% Helvetica, sans-serif; background-color: #efefef; >
Обратите внимание на то, что мы используем @import ‘reset’; в base.scss файле. Когда вы импортируете файл, то не нужно указывать расширение .scss . Sass — умный язык и он сам догадается.
Миксины (примеси)
Некоторые вещи в CSS весьма утомительно писать, особенно в CSS3 , где плюс ко всему зачастую требуется использовать большое количество вендорных префиксов. Миксины позволяют создавать группы деклараций CSS , которые вам придется использовать по нескольку раз на сайте. Вы даже можете передавать переменные в миксины, чтобы сделать их более гибкими. Так же хорошо использовать миксины для вендорных префиксов. Пример для transform :
SCSS Syntax
@mixin transform($property) -webkit-transform: $property; -ms-transform: $property; transform: $property; > .box @include transform(rotate(30deg)); >
Sass Syntax
=transform($property) -webkit-transform: $property -ms-transform: $property transform: $property .box +transform(rotate(30deg))
CSS Output
.box -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); >
To create a mixin you use the @mixin directive and give it a name. We’ve named our mixin transform . We’re also using the variable $property inside the parentheses so we can pass in a transform of whatever we want. After you create your mixin, you can then use it as a CSS declaration starting with @include followed by the name of the mixin.
Расширение/Наследование
Это одна из самых полезных функций Sass. Используя директиву @extend можно наследовать наборы свойств CSS от одного селектора другому. Это позволяет держать ваш Sass-файл в «чистоте». В нашем примере мы покажем вам как сделать стили оповещений об ошибках, предупреждениях и удачных исходах, используя другие возможности Sass, которые идут рука-об-руку с расширением, классами-шаблонами. Класс-шаблон — особый тип классов, который выводится только при использовании расширения — это позволит сохранить ваш скомпилированный CSS чистым и аккуратным.
SCSS Syntax
/* This CSS will print because %message-shared is extended. */ %message-shared border: 1px solid #ccc; padding: 10px; color: #333; > // This CSS won't print because %equal-heights is never extended. %equal-heights display: flex; flex-wrap: wrap; > .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 CSS will print because %message-shared is extended. */ %message-shared border: 1px solid #ccc padding: 10px color: #333 // This CSS won't print because %equal-heights is never extended. %equal-heights display: flex flex-wrap: wrap .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
CSS Output
.message, .success, .error, .warning border: 1px solid #ccc; padding: 10px; color: #333; > .success border-color: green; > .error border-color: red; > .warning border-color: yellow; >
Вышеуказанный код сообщает классам .message , .success , .error и .warning вести себя как %message-shared . Это означает, что где бы не вызывался %message-shared , то и .message , .success , .error и .warning тоже будут вызваны. Магия происходит в сгенерированном CSS , где каждый из этих классов получает css-свойства, как и %message-shared . Это позволит вам избежать написания множества классов в HTML элементах.
Вы можете расширить большинство простых CSS селекторов прибавление к классам-шаблонам в Sass, однако, использование шаблонов — простейший способ быть уверенным, что вы не расширяете класс везде, где он используется в ваших стилях, что могло бы привести к непреднамеренным наборам стилей в вашем CSS.
Когда вы генерируете ваш CSS , то он будет выглядеть как пример ниже. Обратите внимание, %equal-heights не попадает в CSS , так как ни разу не был использован.
Математические операторы
Использовать математику в CSS очень полезно. Sass имеет несколько стандартных математических операторов, таких как + , — , * , / и % . В нашем примере мы совершаем простые математические вычисления для расчета ширины aside и 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%
CSS Output
.container width: 100%; > article[role="main"] float: left; width: 62.5%; > aside[role="complementary"] float: right; width: 31.25%; >
Мы создали простую адаптивную модульную сетку, с шириной в 960 пикселей. Используя математические операторы, мы использовали полученные данные с пиксельными значениями и конвертировали их в процентные, причем без особых усилий. Скомпилированный CSS выглядит так:
Sass © 2006–2018 Hampton Catlin, Natalie Weizenbaum, Chris Eppstein, Jina Anne, и многочисленные участники. Доступно для использования и изменения по лицензии MIT.