Развёрнутое руководство по Sass/SCSS
Современный CSS — мощь, а в комбинации с препроцессорами — вообще боевая машина для оформления контента на страницах. В статье приведено развёрнутое руководство по Sass/SCSS с примерами. После прочтения узнаете, как использовать миксины, переменные и директивы для ещё большего контроля над стилями.
Примечание Весь код Sass/SCSS компилируется в CSS, чтобы браузеры могли его понимать и корректно отображать. В настоящее время браузеры не поддерживают работу с Sass/SCSS или с любым другим препроцессором CSS напрямую, стандартная же спецификация CSS не предоставляет аналогичную функциональность.
Содержание статьи
Зачем использовать Sass/SCSS вместо CSS?
- Вложенность — SCSS позволяет вкладывать правила CSS друг в друга. Вложенные правила применяются только для элементов, соответствующих внешним селекторам (а если речь идёт о Sass, то там и без скобок всё красиво и интуитивно понятно).
- Переменные — в стандартном CSS тоже есть понятие переменных, но в Sass с ними можно работать немного по-другому. Например, повторять их через директиву @for . Или генерировать свойства динамически. Подробнее можете изучить на русскоязычном сайте проекта.
- Улучшенные математические операции— можно складывать, вычитать, умножать и делить значения CSS. В отличие от стандартного CSS, Sass/SCSS позволяют обойтись без calc() .
- Тригонометрия — SCSS позволяет писать собственные (синусоидальные и косинусоидальные) функции, используя только синтаксис Sass/SCSS, подобно тому, как это можно делать в других языках вроде JavaScript.
- Директивы @for , @while и выражение @if-else — можно писать CSS-код, используя знакомые элементы из других языков. Но не обольщайтесь — в итоге на выходе будет обычный CSS.
- Миксины (примеси) — можно один раз создать набор CSS-свойств и работать с ними повторно или смешивать с другими значениями. Миксины можно использовать для создания отдельных тем одного макета. Примеси также могут содержать целые CSS-правила или что-либо другое, разрешённое в Sass-документе. Они даже могут принимать аргументы, что позволяет создавать большое разнообразие стилей при помощи небольшого количества миксинов.
- Функции— можно создавать определения CSS в виде функций для многократного использования.
Препроцессор Sass
Sass не динамичен. У вас не получится генерировать и/или анимировать CSS-свойства и значения в реальном времени. Но можно их создавать более эффективным способом и позволить стандартным свойствам (вроде анимации на CSS) заимствовать их оттуда.
Синтаксис
SCSS особо не добавляет никаких новых возможностей CSS, кроме нового синтаксиса, часто сокращающего время написания кода.
Пререквизиты
Существует 5 CSS-препроцессоров: Sass, SCSS, Less, Stylus и PostCSS.
Эта статья по большей части охватывает SCSS, который похож на Sass. Детальнее об этих препроцессорах можете прочитать на Stack Overflow (оригинал) или на qaru (перевод на русский).
SASS — (.sass) Syntactically Awesome Style Sheets.
SCSS — (.scss) Sassy Cascading Style Sheets.
Расширения .sass и .scss похожи, но всё-таки не одинаковы. Для фанатов командной строки приводим способ конвертации:
Sass — первая спецификация для SCSS с расширением файла .sass . Её разработка началась ещё в 2006 году, но позже был разработан альтернативный синтаксис с расширением .scss .
Обратите внимание Другие препроцессоры функциональностью похожи на SCSS, но синтаксис может отличаться. А ещё, всё то, что работает в CSS, будет также прекрасно воспроизводиться и в Sass, и в SCSS.
Переменные
Sass/SCSS позволяет работать с переменными. В CSS они обозначаются двойным тире ( — ), а в препроцессорах знаком доллара ( $ ).
Вы можете присваивать значение по умолчанию переменным, у которых ещё нет значения, добавив метку !default в конце значения. В таком случае, если переменной уже было присвоено значение, оно не изменится; если же переменная пуста, ей будет присвоено новое указанное значение.
Переменные в Sass могут быть присвоены любому свойству.
Вложенные правила
Стандартные вложенные CSS-элементы с использованием пробела:
Те же вложенные элементы с помощью SCSS:
Как видно, синтаксис выглядит более чистым и менее повторяющимся.
Это особенно полезно при управлении перегруженными макетами. Таким образом, выравнивание, в котором вложенные свойства записаны в коде, полностью соответствует действительной структуре макета приложения.
За кулисами препроцессор всё ещё компилирует его в стандартный код CSS (показано выше), чтобы он мог быть отображён в браузере. Мы лишь изменяем способ написания CSS.
Амперсанд
В SCSS используется директива & .
С помощью символа & вы можете явно указать, где должен быть вставлен родительский селектор.
Результат компиляции Sass (из предыдущего примера) в CSS ниже.
В итоге амперсанд был компилирован в название родительского элемента a ( a:hover ).
Миксины (они же примеси)
Миксины объявляются директивой @mixin . После неё должно стоять имя миксина и, опционально, его параметры, а также блок, содержащий тело миксина. Например, можно определить миксин flexible() , который далее будет включён, например, в класс .centered-elements следующим образом:
Теперь каждый раз после применения класса .centered-elements к HTML-элементу, последний будет преобразован во Flexbox.
Миксины могут также содержать селекторы, в том числе со свойствами. А селекторы могут содержать ссылки на родительский элемент через амперсанд ( & ), вы ведь помните про него?
Пример работы с несколькими браузерами
Некоторые вещи в CSS весьма утомительно писать, особенно в CSS3, где плюс ко всему зачастую требуется использовать большое количество вендорных префиксов( -webkit- или -moz- ).
Миксины позволяют создавать группы деклараций CSS, которые вам придётся использовать несколько раз на сайте. Хорошей практикой будет использование миксинов для вендорных префиксов. Пример:
Арифметические операции
Как и в реальной жизни, вы не можете работать с числами, у которых несовместимы типы данных (например, сложение рх и em ).
Сложение и вычитание
Всегда обращайте внимание на тип складываемых данных. То есть пиксели к пикселям, слоны к слонам. Таким же образом работает вычитание, но со знаком минус.
Умножение
Выполняется точно так же, как в CSS, с помощью calc(a * b) , но без calc и круглых скобок. Кроме того, можно ещё отделять знак умножения пробелами от чисел ( 5*6 == 5 * 6 ).
Исключение Нельзя умножать пиксели между собой. То есть, 10px * 10px != 100px . 10px * 10 == 100px .
Деление
С делением дела обстоят немного сложнее, но разобраться можно, ведь в стандартном CSS косая линия (слэш) зарезервирована для использования краткой формы записи свойств. Пример ниже.
Есть три помощника, которые намекнут на возможность деления:
- Значение (или любая его часть) хранится в переменной или возвращается функцией.
- Значения заключены в круглые скобки.
- Значение используется как часть другого арифметического выражения.
Результат компиляции в CSS:
Остаток
Остаток вычисляет остаток от операции деления. Ниже рассмотрим, как создать «зебру» для HTML-списка.
Создание миксина zebra показано во вставке кода сверху. Директивы @for и @if описаны в секции ниже.
Для создания образца надо написать несколько HTML-элементов.
Результат в браузере:

Зебра успешно сгенерирована миксином zebra
Операторы сравнения

Директива @if принимает выражение SassScript и использует вложенные в неё стили в случае, если выражение возвращает любое значение, кроме false или null .
Ниже показано, как работают директивы @if и @else , вложенные в миксин.
Сравнение в действии. Миксин spacing выберет размеры padding ’а, если тот будет больше, чем margin .
После компиляции в CSS:
Логические операторы

Описание логических операторов
Использование логических операторов Sass для создания кнопки, у которой будет меняться фон в зависимости от её ширины.
Строки
В CSS определено 2 типа строк: с кавычками и без. Sass распознаёт и то, и другое. В итоге вы получите в CSS тот тип строк, который использовали в Sass.
В некоторых случаях можно добавить строки в допустимые значения CSS без кавычек, но только если добавленная строка является завершающим элементом.
Пример ниже демонстрирует, как делать не надо.
Можете складывать строки разных типов, если в них нет пробелов. Пример ниже не будет скомпилирован.
Строки, содержащие пробелы, должны быть отделены кавычками. Решение проблемы:
Пример сложения нескольких строк:
Сложение строк и чисел:
Обратите внимание Свойство content работает только с псевдоселекторами :before и :after . Рекомендуется не использовать content в CSS-документе, а напрямую использовать его между тегами в HTML.
Операторы управления потоками
В SCSS есть функции ( function() ) и директивы ( @directive ). Чуть выше мы уже рассматривали пример функции, когда изучали передачу аргументов внутри миксинов.
Функции обычно заключаются в скобки, следующие сразу за её именем. А директива начинается с символа @ .
Подобно JavaScript, SCSS позволяет работать со стандартным набором операторов управления потоками.
if() — это функция (и иногда основа искусственного интеллекта).
Её использование выглядит довольно примитивным: оператор вернёт одно из двух обозначенных в условии значений.
@if — это директива, использующаяся для разветвления на основе условия.
Ниже показано комбо-разветвление с добавлением директивы @else .
Проверка на наличие родительского элемента
Амперсанд выбирает родительский элемент, если тот существует. В ином случае вернёт null . Поэтому может использоваться совместно с директивой @if .
В следующих примерах рассмотрим создание условных CSS-стилей в зависимости от наличия родительского элемента.
Директива @for
Директива @for выводит набор стилей заданное число раз. Для каждого повторения используется переменная-счётчик для изменения вывода.
Директива @for итерируется 5 раз.
Результат компиляции в CSS:
Директива @each
Директива @each устанавливает $var в каждое из значений списка или словаря и выводит содержащиеся в ней стили, используя соответствующее значение $var .
Результат компиляции в CSS:
Директива @while
Директива @while принимает выражение SassScript и циклично выводит вложенные в неё стили, пока выражение вычисляется как true . Она может быть использована для создания более сложных циклов, чем таких, для которых подходит @for , хотя она бывает необходима довольно редко. Например:
Функции в Sass/SCSS
Используя Sass/SCSS можно использовать функции так же, как и в других языках.
Создадим функцию three-hundred-px() , возвращающую 300px.
После применения класса .name ширина элемента будет равна 300 пикселям.
Результат в браузере:

Функции в Sass могут возвращать любое корректное значение CSS и могут быть назначены любому свойству. Они даже могут быть рассчитаны на основе переданного аргумента.
Тригонометрия
Тригонометрические функции sin() и cos() часто встречаются в виде встроенных классов во многих языках, таких как JavaScript, например.
Их работу стоит изучать, если нужно сократить время, затрачиваемое на разработку анимаций пользовательского интерфейса, например для создания троббера. Мы, кстати, уже говорили об этом в одной из статей. Но в данном случае это будет код, а не gif-картинка, вставленная в HTML-документ.
Ниже рассмотрим пару примеров для создания интересных анимационных эффектов с помощью функции sin() , в которых количество кода сведено к минимуму. Далее можете масштабировать эти знания на создание интерактивных элементов пользовательского интерфейса (движение по кругу, волнистая анимация).
Преимущество использования тригонометрии в сочетании с CSS выражается в отсутствии дополнительных HTTP-запросов, как это происходит с gif-изображениями.
Можно писать тригонометрические функции на Sass. Об этом читайте далее.
Написание собственных функций
В тригонометрии многие операции основаны на функциях. Каждая функция строится на основе другой. Например, функция rad() требует использования PI() . Функции cos() и sin() требуют использование rad() .
Написание функций на Sass/SCSS очень похоже на написание функций в других языках.
Использование функции pow() :
Использование функции rad() :
Для вычисления тангенса функцией tan() нужно применить функции sin() и cos() .
Заключение
Как видите, CSS уже достаточно эволюционировал, чтобы порой заменять JavaScript. Это упрощает работу и экономит время. Кстати, загляните в одну из наших статей, в которой описаны возможности современного CSS.
Introduction
Developers have always preferred CSS for web designing and development in recent years. SASS (Syntactically Awesome Style Sheets) reduced CSS’s market share. SCSS, an advanced version of SASS, is replacing CSS. CSS and SCSS have altered the way web developers create websites, particularly layouts. It has used tables to make them, a process that is either gone or not the only option. In order to achieve their desired effects, developers can now use gradients and rounded corners without relying on background images.
With CSS and SCSS, developers are able to separate HTML files from design and formatting, simplifying and streamlining the web design process. Despite this, CSS and SCSS are often debated. Thankfully. This article aims to help you decide which one to choose by comparing them in detail. So let’s look at how CSS and SCSS differ.
What is CSS?
The Cascading Style Sheets language, more commonly referred to as CSS, is a styling language that gives web designers and developers the ability to control the appearance of a web page. Hakon Wium Lie proposed CSS for the first time on October 10th, 1994. However, in 1996, the W3C issued the first CSS recommendation (CSS1).
HTML only allows us to specify the dimensions of a page, not its aesthetic appeal. CSS comes into play here. By using CSS, we can employ a variety of features to make a website appear attractive or professional. This allows us to change the structure of the tables or divisions, color the text, set the margin and padding, and select the text font.
In simple terms, we could describe this as the language that is used to modify the display or structure of a web page. The most basic description we can give of this is that it is what is used to enhance a web page. Typically, a web page comprises the structure, design, and client site functionality. The structure is provided by HTML, and CSS provides the design.
CSS3 was launched many years ago, and since then, no new version has been released. Using this version, you can round the border without any difficulties, and the developers who were struggling to do so in CSS can breathe a sigh of relief because the problem has been solved. Despite CSS3’s ease of use, you may still need the assistance of a CSS3 developer in certain instances.
Example of CSS
Internal CSS
It is possible to define an internal style for a single HTML document.
Internal styling is defined in the <head> section of an HTML page, within a <style> element:
External CSS
The style for many pages is defined by an external style sheet. It’s easy to change the appearance of an entire website simply by changing a single file in an external style sheet!
To use an external style sheet, add a link to it in the <head> section of the HTML page:
CSS Fonts
CSS’s color property determines the color of the HTML element’s text.
An HTML element’s font family is specified using the CSS font-family property.
Text size is defined by the CSS font-size property.
CSS Selectors
Selecting the material you want to style in your document is done with the use of CSS selectors. The CSS ruleset includes selectors as one of its components. Selectors in CSS choose HTML components based on a variety of criteria, including their id, class, attribute, etc.
There are several different types of selectors in CSS.
- CSS Element Selector
- CSS Id Selector
- CSS Class Selector
- CSS Universal Selector
- CSS Group Selector
1. CSS Element Selector
The element selector picks HTML elements based on their names.
2. CSS Id Selector
A particular element can be chosen using the id selector, which works by selecting the id attribute of an HTML element. Because an id will always be distinct inside the page, it can be used to choose just one of a given kind of element. It is represented by the hash character (#), and then the id of the element that is being referenced comes next.
Take this example with the identifier “para1,” for instance.
3. CSS Class Selector
The class selector is used to select HTML items having a certain class property. It is used with a period symbol . (full stop symbol).
Let’s take an example with a class “center”.
4. CSS Universal Selector
The universal selector is used as a wildcard character. It selects all the elements on the pages.
5. CSS Group Selector
This selector is used to pick all items with identical style declarations. Grouping selection is used to reduce the amount of code. In grouping, commas are used to separate each selector.
Let’s look at the CSS code that doesn’t use a group selector.
CSS Properties
There are many CSS properties that are available, but we will look into those that are pretty common and used a lot to build a solid foundation first.
Color
If you are a developer, you are likely familiar with it as it is utilized frequently. In case you don’t remember, the color property is used to specify the color of the text within an HTML element. This applies to any HTML element that has text content, including <h1>-<h6> , <p> , <a> and more.
Color values can be expressed in several formats, but the most common are hex values, RGB, and named colors.
Font-size
The font-size property sets the size of the text. Being able to manage the text size is important in web design. However, you should not use font size adjustments to make paragraphs look like headings, or headings look like paragraphs. Always use the proper HTML tags, like <h1> — <h6> for headings and <p> for paragraphs. The font-size value can be an absolute, or relative size.
Height/Width
The height and width properties define the height and width, respectively, of an HTML element. There are numerous possible values for both of these attributes, including pixels and percentages, etc.
Border
It is possible to set a border for your HTML element using the border property. This allows you to create a border around your <img> tag.
CSS Advantages
- With the help of Cascading Style Sheet, you can automatically apply necessary styles several times after repeating styling for an element once.
- CSS provides uniform styling across various websites. A single instruction can apply to many areas.
- To increase site speed, web designers must use fewer lines of code per page.
- Since a change to a single line of code will affect the whole website, CSS simplifies the building of websites as well as website maintenance.
- It is less complicated.
- With the help of CSS, you are able to make consistent and spontaneous changes.
- Changes to CSS property are device-friendly.
- It is capable of repositioning.
- These enormous reductions in bandwidth are caused by insignificant tags that are distinct from a lot of pages.
- User-friendly customization of the online page.
- It reduces the size of the file transfer.
CSS Disadvantages
- What works in one browser may not always work in another with CSS. Web developers must test the program’s compatibility across multiple browsers.
- There is a lack of security.
- CSS language may become complicated when third-party tools such as Microsoft FrontPage are utilized.
- It is important to verify compatibility if any issues arise after implementing the modifications. The changes affect all browsers.
- The world of programming languages is complex for non-developers. Different levels of CSS, such as CSS, CSS 2, and CSS 3, are frequently quite confusing.
- There are multiple levels that create confusion for non-developers and beginners.
What is SCSS?
SCSS is superior to CSS. Syntactically Awesome Style Sheets (SASS) contain a special file called SCSS. SCSS is the improved solution to CSS. Hampton Catlin designed SCSS, which was then developed by Chris Eppstein and Natalie Weizenbaum. Because of its extensive features, it is commonly referred to as Sassy CSS. The file extension for SCSS is .scss.
Using SCSS, we can extend the capabilities of CSS to include variables, nesting, and more. All of these additional features can make writing CSS simpler and quicker.
By executing SCSS files on the server hosting your web application, SCSS generates standard CSS that the browser can comprehend. Reading SASS or SCSS code is faster than reading CSS code.
SCSS Example
SASS and SCSS examples can simply be created. Follow these steps:
Here is an example of how to use SCSS in HTML. Create an HTML file with the following code:
SCSS Variables
Even if you never use any of SCSS’s other features, variables would be reason enough to compile CSS. As we have described, variables are very useful. Let’s look at how.
You can define a variable in the same way you define a CSS rule. The basic syntax is to use a $ before the variable name and to treat the definition like you would any other CSS rule.
Sass Variable Syntax : $<variable name>:<value>;
This substitution will be handled by the Sass transpiler:
Scope
The scope concept is supported by Sass variables as well. Variables are only available at the level of nesting where they are defined. Here’s an example:
SCSS Variable Scope
Can you determine the color of the text included within and <a> tag? It will be red in color. The second definition $main-color: blue; will only be accessible within the rules for the <p> tag. The following CSS has been translated.
SCSS Nested Syntax
SCSS Nested Rules
Scss lets you nest CSS selectors in the same way as HTML.
Look at an example of some Sass code for a site’s navigation:
Scss nests the ul, li, and selectors within the nav selector.
Unlike CSS, which defines each rule individually (not nested):
CSS Syntax
Sass Nested Properties
Numerous CSS properties share the same prefix, such as font family, font-size, and font-weight, as well as text-align, text-transform, and text overflow.
They can be expressed as nested properties in Sass:
SCSS Syntax
CSS Output
SCSS Mixins
By using the @mixin the directive, you can create CSS code that can be reused throughout your website.
@include allows you to use (include) the mixin.
Sass @include mixin Syntax:
So, to include the important-text mixin created above:
SCSS Syntax
The Sass transpiler will convert the above to normal CSS:
CSS Output
A mixin can also include other mixins:
SCSS Syntax
SCSS Advantages
- You can use SCSS to write clean, simple, and concise CSS.
- It contains fewer codes, so CSS can be written faster.
- It is more stable, powerful, and elegant because it is an extension of CSS. This makes it easier for designers and developers to work more efficiently and quickly.
- It’s compatible with all CSS versions. So, you can use any available CSS library.
- It offers to nest so that you can use nested syntax and useful functions such as color manipulation, mathematical functions, and other values.
SCSS Disadvantages
- The developer must devote sufficient time to learning about its new features before using this preprocessor.
- Using Sass could result in the loss of the browser’s native element inspector.
- The code requires compilation.
- Complex Troubleshooting.
- The knowledge of SCSS helps to customize Bootstrap 4.
CSS vs SCSS: Who Won?
The difference between CSS and SCSS has now been outlined in great detail. You now have access to every piece of knowledge there is to know about the two, whether it be the definition, the qualities, the advantages, or the disadvantages. According to us, valid SCSS provides all the functionality of CSS and additional features not found in CSS, making it an excellent alternative for web designers. SCSS is loaded with extensive capabilities. SCSS enables variables and by utilizing variables, you can shorten your code. It is a significant improvement over standard CSS.
So in this battle of CSS vs SCSS, you will decide which of the two options is the better fit for your requirements by analyzing the benefits and drawbacks of each. You are now in control of the situation, given that the knowledge is available to you. Make sure that you go with the alternative that will yield the best results. Also, have a look at our Blog on Top Web Design Trends You Should Not Miss in 2023.
What is the difference between CSS and SCSS?
I know CSS very well, but am confused about Sass. How is SCSS different from CSS, and if I use SCSS instead of CSS will it work the same?
![]()
6 Answers 6
In addition to Idriss answer:
In CSS we write code as depicted bellow, in full length.
In SCSS we can shorten this code using a @mixin so we don’t have to write color and width properties again and again. We can define this through a function, similarly to PHP or other languages.
In SASS however, the whole structure is visually quicker and cleaner than SCSS.
-
It is sensitive to white space when you are using copy and paste,
It seems that it doesn’t support inline CSS currently.
![]()
CSS is the styling language that any browser understands to style webpages.
SCSS is a special type of file for SASS , a program written in Ruby that assembles CSS style sheets for a browser, and for information, SASS adds lots of additional functionality to CSS like variables, nesting and more which can make writing CSS easier and faster.
SCSS files are processed by the server running a web app to output a traditional CSS that your browser can understand.
![]()
css has variables as well. You can use them like this:
![]()
![]()
Variable definitions right:
All answers is good but question a little different than answers
«about Sass. How is SCSS different from CSS» : scss is well formed CSS3 syntax. uses sass preprocessor to create that.
and if I use SCSS instead of CSS will it work the same? yes. if your ide supports sass preprocessor. than it will work same.
Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.
The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension .sass.
- Furher Information About:
What Is A CSS Preprocessor?
CSS in itself is devoid of complex logic and functionality which is required to write reusable and organized code. As a result, a developer is bound by limitations and would face extreme difficulty in code maintenance and scalability, especially when working on large projects involving extensive code and multiple CSS stylesheets. This is where CSS Preprocessors come to the rescue.
A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through its own scripting language. It helps us to use complex logical syntax like – variables, functions, mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS. By using CSS Preprocessors, you can seamlessly automate menial tasks, build reusable code snippets, avoid code repetition and bloating and write nested code blocks that are well organized and easy to read. However, browsers can only understand native vanilla CSS code and will be unable to interpret the CSS Preprocessor syntax. Therefore, the complex and advanced Preprocessor syntax needs to be first compiled into native CSS syntax which can then be interpreted by the browsers to avoid cross browser compatibility issues. While different Preprocessors have their own unique syntaxes, eventually all of them are compiled to the same native CSS code.
Moving forward in the article, we will take a look at the 3 most popular CSS Preprocessors currently being used by developers around the world i.e Sass, LESS, and Stylus. Before you decide the winner between Sass vs LESS vs Stylus, let us get to know them in detail first.
Sass – Syntactically Awesome Style Sheets
Sass is the acronym for “Syntactically Awesome Style Sheets”. Sass is not only the most popular CSS Preprocessor in the world but also one of the oldest, launched in 2006 by Hampton Catlin and later developed by Natalie Weizenbaum. Although Sass is written in Ruby language, a Precompiler LibSass allows Sass to be parsed in other languages and decouple it from Ruby. Sass has a massive active community and extensive learning resources available on the net for beginners. Thanks to its maturity, stability and powerful logical prowess, Sass has established itself to the forefront of CSS Preprocessor ahead of its rival peers.
Sass can be written in 2 syntaxes either using Sass or SCSS. What is the difference between the two? Let’s find out.
Syntax Declaration: Sass vs SCSS
- SCSS stands for Sassy CSS. Unlike Sass, SCSS is not based on indentation.
- .sass extension is used as original syntax for Sass, while SCSS offers a newer syntax with .scss extension.
- Unlike Sass, SCSS has curly braces and semicolons, just like CSS.
- Contrary to SCSS, Sass is difficult to read as it is quite deviant from CSS. Which is why SCSS it the more recommended Sass syntax as it is easier to read and closely resembles Native CSS while at the same time enjoying with power of Sass.
Consider the example below with Sass vs SCSS syntax along with Compiled CSS code.
In both cases, be it Sass or SCSS, the compiled CSS code will be the same –
Usage of Sass
Arguably the most Popular front end framework Bootstrap is written in Sass. Up until version 3, Bootstrap was written in LESS but bootstrap 4 adopted Sass and boosted its popularity. A few of the big companies using Sass are – Zapier, Uber, Airbnb and Kickstarter.
LESS – Leaner Style Sheets
LESS is an acronym for “Leaner Stylesheets”. It was released in 2009 by Alexis Sellier, 3 years after the initial launch of Sass in 2006. While Sass is written in Ruby, LESS is written JavaScript. In fact, LESS is a JavaScript library that extends the functionality of native vanilla CSS with mixins, variables, nesting and rule set loop. Sass vs LESS has been a heated debate. It is no surprise that LESS is the strongest competitor to Sass and has the second-largest user base. However, When bootstrap dumped LESS in favor of Sass with the launch of Bootstrap 4, LESS has waned in popularity. One of the few disadvantages of LESS over Sass is that it does not support functions. Unlike Sass, LESS uses @ to declare variables which might cause confusion with @media and @keyframes. However, One key advantage of LESS over Sass and Stylus or any other preprocessors, is the ease of adding it in your project. You can do that either by using NPM or by incorporating Less.js file. Syntax Declaration: LESS Uses .less extension. Syntax of LESS is quite similar to SCSS with the exception that for declaring variables, instead of $ sign, LESS uses @.
Usage Of LESS The popular Bootstrap framework until the launch of version 4 was written in LESS. However, another popular framework called SEMANTIC UI is still written in LESS. Among the big companies using Sass are – Indiegogo, Patreon, and WeChat
Stylus
The stylus was launched in 2010 by former Node JS developer TJ Holowaychuk, nearly 4 years after the release of Sass and 1 year after the release of LESS. The stylus is written Node JS and fits perfectly with JS stack. The stylus was heavily influenced by the logical prowess of the Sass and simplicity of LESS. Even though Stylus is still popular with Node JS developers, it hasn’t managed to carve out a sizeable share for itself. One advantage of Stylus over Sass or LESS, is that it is armed with extremely powerful built-in functions and is capable of handling heavy computing.
Syntax Declaration: Stylus Uses .styl extension. Stylus offers a great deal of flexibility in writing syntax, supports native CSS as well as allows omission of brackets colons and semicolons. Also, note that Stylus does not use @ or $ symbols for defining variables. Instead, Stylus uses the assignment operators to indicate a variable declaration.
CSS vs SCSS
CSS is one of the foundations of web development. It has been there for years. But ever since SCSS has been developed, CSS has got a tough competition from it. So what is it that makes SCSS better than CSS? Read more to know the differences between both of them.
Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language like HTML. CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript.

CSS is designed to enable the separation of presentation and content, including layout, colors, and fonts. This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics, enable multiple web pages to share formatting by specifying the relevant CSS in a separate .css file and reduce complexity and repetition in the structural content.
The basic idea behind CSS is to separate the structure of a document from the presentation of the document. HTML is meant for structure. It was never intended for anything else. All those attributes you add to style your pages were added later as the viewing public demanded it. All those additions though make HTML clumsy and work against its main purpose of structuring a document. HTML is there to let a browser know that this block of text is a paragraph and that block of text is a heading for this paragraph.
Advantages of CSS
- Easier to maintain and update
- Greater consistency in design
- More formatting options
- Lightweight code
- Faster download times
- Search engine optimization benefits
- Ease of presenting different styles to different viewers
- Greater accessibility
Disadvantages of CSS
- It ould be easily overridden
- It takes more time to download a CSS file than an HTML file.
- It becomes complicated because of different versions.
SASS or SCSS (short for syntactically awesome style sheets) is a style sheet language initially designed by Hampton Catlin and developed by Natalie Weizenbaum. After its initial versions, Weizenbaum and Chris Eppstein have continued to extend Sass SassScript, a scripting language used in Sass files.

Sass consists of two syntaxes. The original syntax, called «the indented syntax,» uses a syntax similar to Haml. It uses indentation to separate code blocks and newline characters to separate rules. The newer syntax, «SCSS» (Sassy CSS), uses block formatting like that of CSS. It uses braces to denote code blocks and semicolons to separate rules within a block. The indented syntax and SCSS files are traditionally given the extensions .sass and .scss, respectively.
Advantages of SCSS
- It contains fewer codes so you can write CSS quicker.
- It is more stable, powerful, and elegant because it is an extension of CSS, making it easy for designers and developers to work more efficiently and quickly.
- It is compatible with all versions of CSS. So, you can use any available CSS libraries.
- It provides nesting so you can use nested syntax and useful functions like color manipulation, math functions, and other values.
Disadvantages of SCSS
- The developer must have enough time to learn new features present in this preprocessor before using it.
- Using SCSS may cause losing benefits of the browser’s built-in element inspector.
- Debugging becomes harder in case of SCSS
- It can produce very large CSS files.
Now that the brief description of both CSS and SCSS is done, we will discuss the comparison between CSS and SCSS