In this tutorial, we aim to simplify your CSS code using SASS/SCSS variables. By the end of this guide, you will have learned how to define, use and manipulate SCSS variables to make your stylesheets cleaner, more efficient, and easier to maintain.
The prerequisite for this tutorial is a basic understanding of HTML and CSS. Prior knowledge of SASS/SCSS is not necessary, but it could be beneficial.
SASS/SCSS allows you to declare variables that can store values, such as color codes or font sizes, and use them throughout your stylesheet. This way, you can make changes in one place and have them reflect everywhere the variable is used.
To declare a variable in SASS/SCSS, you use the $
symbol followed by the variable name and a value. For example:
$primary-color: #ff6347;
Now, you can use this variable throughout your stylesheet like this:
body {
background-color: $primary-color;
}
This would compile to the following CSS:
body {
background-color: #ff6347;
}
Let's take a look at a few more examples of SASS/SCSS variables in action.
$font-stack: Helvetica, sans-serif;
$primary-font-size: 16px;
body {
font: $primary-font-size $font-stack;
}
In the above code, we're setting the font and font-size for the body element using variables. This will compile to:
body {
font: 16px Helvetica, sans-serif;
}
$standard-margin: 1em;
$standard-padding: 1em;
.container {
margin: $standard-margin;
padding: $standard-padding;
}
In this example, we're using variables for margin and padding values. This compiles to:
.container {
margin: 1em;
padding: 1em;
}
In this tutorial, you have learned how to define, use, and manipulate SASS/SCSS variables to create more maintainable stylesheets. The next step is to learn about other SASS/SCSS features, like mixins, nesting, and functions.
For more information, you can visit the official SASS documentation.
Exercise 1: Create a SCSS file with variables for primary color, secondary color, font size, and margin. Use these variables in at least five different selectors.
Exercise 2: Modify the SCSS file from the first exercise so that it uses a variable for the font stack (font family). Apply this font stack to at least three different selectors.
Solutions:
$primary-color: #ff6347;
$secondary-color: #4f94cd;
$font-size: 14px;
$margin: 1em;
body {
color: $primary-color;
font-size: $font-size;
margin: $margin;
}
h1 {
color: $secondary-color;
margin-bottom: $margin;
}
p {
color: $primary-color;
margin-bottom: $margin;
}
$primary-color: #ff6347;
$secondary-color: #4f94cd;
$font-size: 14px;
$margin: 1em;
$font-stack: Arial, sans-serif;
body {
color: $primary-color;
font: $font-size $font-stack;
margin: $margin;
}
h1 {
color: $secondary-color;
font: $font-size $font-stack;
margin-bottom: $margin;
}
p {
color: $primary-color;
font: $font-size $font-stack;
margin-bottom: $margin;
}
Remember, practice is key when learning new concepts. Keep experimenting with different values and selectors to get a better grasp of SASS/SCSS variables.