Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Variables

A variable stores a value under a name so you can reuse it: a colour, a size, a font. In Sass a variable name starts with $. When the site's main colour changes, you edit one line instead of searching the whole project.

Declaring and using

A variable is declared like a CSS property: name, colon, value. Write it in styles/main.scss:

// styles/main.scss
$primary: #2563eb;
$radius: 8px;
 
.btn {
  color: white;
  background: $primary;
  border-radius: $radius;
}

After compiling there are no variables left — only their values:

.btn {
  color: white;
  background: #2563eb;
  border-radius: 8px;
}

Any CSS value fits

A variable can hold a number with a unit, a colour, a string or a whole list of values:

// styles/main.scss
$font-main: system-ui, sans-serif;
$shadow: 0 2px 8px rgb(0 0 0 / 0.15);
$gap: 16px;
 
.card {
  padding: $gap;
  font-family: $font-main;
  box-shadow: $shadow;
}
.card {
  padding: 16px;
  font-family: system-ui, sans-serif;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
<style>
  .card {
    padding: 16px;
    font-family: system-ui, sans-serif;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
</style>
 
<div class="card">Card with a shadow</div>

Note that Sass wrote the shadow colour as rgba() — for the browser it is the same colour.

Scope

A variable declared at the top of a file is visible everywhere below. A variable declared inside a rule is local: it exists only inside the braces.

// styles/main.scss
.card {
  $inner-gap: 12px;
  padding: $inner-gap;
}

Using $inner-gap outside .card is an error: Undefined variable.

Sass variables and custom properties

You already know CSS custom properties like --primary. They look similar but work at different times:

Sass $primaryCSS --primary
When it worksWhile compiling, on your computerIn the browser, while the page is open
In the final CSSReplaced with the valueStays as var(--primary)
Changes in media queries and from JavaScriptNoYes
Inherited by child elementsNoYes
Usable in selectors and media query conditionsYesNo

Use Sass variables for constants of the code — breakpoints, sizes, the source colours. Use custom properties for values that must change on the page, like a dark theme. Later in the course they work together.

Common mistake

A Sass variable cannot be "switched" by a media query. This code looks like it enlarges the padding on wide screens:

// styles/main.scss
$gap: 16px;
 
.card {
  padding: $gap;
}
 
@media (min-width: 768px) {
  $gap: 32px;
}

But the value was already substituted when .card was compiled, and the empty media query is dropped:

.card {
  padding: 16px;
}

Write the new value inside the media query instead: @media (min-width: 768px) { .card { padding: 32px; } } — or use a custom property.

Thanks for reading!

Donate to the site — we work hard for you.