
Modern CSS Techniques: 10 Features to Try
11/05/2024How to Hide the reCAPTCHA v3 Badge with CSS
12/05/2024
Sass stands for Syntactically Awesome Style Sheets. This tutorial shows how to use it to create reusable styles and compile them to CSS.
1. What is a CSS preprocessor?
A CSS preprocessor extends the authoring language with features and abstractions that help you maintain complex stylesheets.
Sass, Less, and Stylus are examples. Browsers read the standard CSS these tools generate, so compile their source files before deploying the site.
You can compile Sass with command-line tools, code editor extensions, or task runners such as Gulp and Grunt.
2. Why learn Sass?
Sass can help front-end developers and designers in several ways:
- Efficiency: Variables, nesting, and functions let you avoid repetition and organize styles.
- Reuse: Functions and mixins help share calculations or groups of declarations across a project.
- Variables: Store shared values such as colors, font sizes, and spacing. Update the source value and recompile to update references.
- Nesting: Group related selectors to reflect the relevant HTML structure. Keep the resulting selectors shallow enough to maintain.
- Modularity: Split stylesheets into modules or partials to organize larger projects.
- Maintenance: Make changes in the relevant module rather than searching through one large stylesheet.
- Existing CSS: Introduce Sass gradually. You can start with one section or component.
- Tools and community: Sass has an ecosystem of development tools and libraries, alongside open-source examples.
- Transferable concepts: Working with Sass also introduces ideas used by preprocessors such as Less and Stylus.
3. Install Sass with Node.js
Install Node.js, then install the Sass package using npm:
Install Node.js from the official Node.js website.
Install the Sass package:
- Open a terminal or command prompt on your system.
- Run the following command using npm, the Node.js package manager:
npm install -g sass
The -g option installs a command you can use from any directory. For a shared project, you can install Sass as a project dependency and run it through an npm script instead.
- Verify that the command works:
sass --version
The screenshot shows Dart Sass 1.69 being installed from the Windows command prompt.

Dart Sass is the primary Sass implementation.
You can now compile .scss or .sass files into CSS. Section 5 covers command-line compilation.
See the Dart Sass documentation for other installation methods.
4. Sass fundamentals
The next sections introduce the Sass features you can use to make styles more reusable and easier to read.
4.1. Variables
Start a Sass variable’s name with $ and assign it a value. Variables can hold numbers, colors, strings, and other Sass values. See the Sass value types.
$name: value;
The example defines variables for primary and secondary colors, font size, and spacing, then uses them in heading and button rules.
// Define variables
$color-primario: #3498db;
$color-secundario: #e74c3c;
$tamano-fuente: 16px;
$espaciado: 20px;
// Use variables
.encabezado {
background-color: $color-primario;
font-size: $tamano-fuente;
padding: $espaciado;
}
.boton {
background-color: $color-secundario;
font-size: $tamano-fuente;
margin: $espaciado;
}
4.2. Comments
SCSS supports two types of comments:
- Single-line comments: Start them with
//. This syntax is available in SCSS source.
Single-line comments are omitted from compiled CSS.
// A single-line Sass comment. The compiled CSS omits it. $color-primario: #3498db; // Set a primary color.
- Block comments: Write them between
/*and*/, as in CSS.
Ordinary block comments can appear in the expanded output and are removed in compressed output.
A block comment beginning with /*! is kept even in compressed output, for example to retain a license notice.
/* This is a multiline Sass comment.
It can span more than one line.
Se incluye en el fichero CSS al compilar, salvo en modo COMPRESSED*/
.elemento-desactivado {
display: none;
}
Compressed output removes unnecessary characters. Section 5 shows how to request it.
4.3. Nesting
Sass can nest selectors inside each other. A nested rule can compile to a selector for descendants of the outer selector. Only inheritable CSS properties pass automatically from a parent element to its children.
Start with this markup:
<div class="contenedor"> <h1>Heading</h1> <p>Example paragraph</p> </div>
Represent the structure with nested SCSS rules:
.contenedor {
background-color: #f0f0f0;
padding: 20px;
h1 {
font-size: 24px;
color: #333;
}
p {
font-size: 16px;
color: #666;
}
}
In this example:
.contenedoris the outer selector.- The
h1andprules are nested inside it. - After compilation, the heading and paragraph rules match descendants of
.contenedor. The outer rule styles the container itself.
This compiles to the following CSS:
.contenedor {
background-color: #f0f0f0;
padding: 20px;
}
.contenedor h1 {
font-size: 24px;
color: #333;
}
.contenedor p {
font-size: 16px;
color: #666;
}
4.4. Using the parent selector &
Use & in a nested rule to refer to the current outer selector. This is useful for pseudo-classes or related selectors.
For example:
.button {
background-color: blue;
&:hover {
background-color: red;
}
}
Here &:hover compiles to .button:hover, so the red background applies to the button itself while it is hovered.
4.5. Sass lists
A Sass list is an ordered sequence of values. Items can be separated by commas or spaces. Quote strings when the syntax or the value requires it.
$colores: red, green, blue, yellow; // Comma-separated values $colores: red green blue yellow; // Space-separated values $colores: 'red' 'green' 'blue' 'yellow'; // Quoted values
List indexing starts at 1. Access an item by its position, as shown below.
$primer-color: nth($colores, 1); // red $segundo-color: nth($colores, 2); // green
The list functions in the table cover additional operations:
| Function | Description | Example |
|---|---|---|
| length($list) | Returns the number of items in $list. | length(1 2 3) returns 3 |
| index($list, $value) | Returns the one-based index of the first matching value, or null if absent. | index(apples oranges bananas, oranges) returns 2 |
| join($list1, $list2[, $separator]) | Combina $list1 y $list2 usando $separator como separador en la lista resultante. Por defecto toma el separador de $list1. | join(1 2 3, 4 5 6, comma) returns 1, 2, 3, 4, 5, 6 |
| append($list, $value[, $separator]) | Agrega $value al final de $list, utilizando $separator como separador. Por defecto toma el separador de $list. | append(1 2 3, 4) returns 1 2 3 4 |
Use these functions to count items, locate a value, combine lists, or append a new item.
4.6. Sass maps
A map stores key-value pairs. Write each pair as key: value and separate pairs with commas inside parentheses.
$botones: ( primary: #3498db, secondary: #e74c3c, success: #2ecc71 );
Look up a value by its key. The example uses the legacy global function map-get(); its module equivalent is map.get().
$color-primary: map-get($botones, primary); // #3498db $color-secondary: map-get($botones, secondary); // #e74c3c
The sass:map module also provides map.merge(), map.keys(), and map.values(). Older code may use their global equivalents.
4.7. Control flow
Use control directives to generate styles conditionally or repeat a rule without duplicating source code.
if: Includes declarations when a condition is true.
$color: blue;
.element {
@if $color == blue {
background-color: $color;
} @else {
background-color: red;
}
}
Output:
.element {
background-color: blue;
}
for: Generates rules over a numeric range.
@for $i from 1 through 3 {
.element-#{$i} {
font-size: 10px * $i;
}
}
Output:
.element-1 {
font-size: 10px;
}
.element-2 {
font-size: 20px;
}
.element-3 {
font-size: 30px;
}
each: Iterates over a list or map.
$colors: red, green, blue;
@each $color in $colors {
.element-#{$color} {
background-color: $color;
}
}
Output:
.element-red {
background-color: red;
}
.element-green {
background-color: green;
}
.element-blue {
background-color: blue;
}
while: Repeats while a condition remains true.
$i: 1;
@while $i < 4 {
.element-#{$i} {
width: 100px * $i;
}
$i: $i + 1;
}
Output:
.element-1 {
width: 100px;
}
.element-2 {
width: 200px;
}
.element-3 {
width: 300px;
}
4.8. Functions
Sass includes functions for manipulating colors, numbers, maps, lists, and strings. The examples below include familiar legacy names. Use their module equivalents in new code when available.
- lighten($color, $amount): Legacy function that increases HSL lightness by the given amount. In modern Sass, use
color.adjust()with the lightness adjustment.
$color: #3498db;
$lighter-color: lighten($color, 20%); // Lighten the color by 20%
h1{ color: $lighter-color;}
Output:
h1 {
color: #8bc4ea;
}
- darken($color, $amount): Legacy function that decreases HSL lightness. Use
color.adjust()with a negative lightness value for equivalent behavior.
$color: #e74c3c;
$darker-color: darken($color, 10%); // Darken the color by 10%
h1{ color: $darker-color;}
Output:
h1 {
color: #d62c1a;
}
- rgba($color, $alpha): Sets a color’s alpha value in this example.
$color: #3498db; $semi-transparent: rgba($color, 0.5); // Set the opacity to 50%
- round($number): Rounds to the nearest integer. The module form is
math.round().
$value: 3.7; $rounded-value: round($value); // Round to 4
- map-get($map, $key): Looks up a key. The module form is
map.get().
$colors: (primary: #3498db, secondary: #e74c3c); $primary-color: map-get($colors, primary); // Get the primary color
- nth($list, $n): Retrieves a list item by position. The module form is
list.nth().
$numbers: 1px 2px 3px 4px 5px; $third-element: nth($numbers, 3); // Get the third item (3px)
- str-length($string): Returns the string length. The module form is
string.length().
$text: "Hello world!"; $text-length: str-length($text); // Get the string length (12)
- unquote($string): Removes string quotes. The module form is
string.unquote().
$quoted-text: '"This is quoted text"';
$unquoted-text: unquote($quoted-text); // Remove the quotes ("This is quoted text")
4.9. Mixins
Mixins are reusable blocks of Sass that can emit declarations and rules wherever you include them.
Define a mixin with , its name, and any parameters it accepts.
mixin
@mixin box-shadow($x, $y, $blur, $color) {
box-shadow: $x $y $blur $color;
}
This box-shadow mixin accepts four parameters: $x, $y, $blur, and $color.
Use and pass any required arguments:
include
.element {
@include box-shadow(2px, 2px, 4px, #888);
}
The compiler emits the corresponding CSS declaration:
.element {
box-shadow: 2px 2px 4px #888;
}
4.9.1. Mixins with default parameters
Give parameters default values when you want callers to be able to omit them.
@mixin box-shadow($x: 0, $y: 0, $blur: 4px, $color: #000) {
box-shadow: $x $y $blur $color;
}
When an argument is omitted, the mixin uses its default:
.element {
@include box-shadow;
}
The result is:
.element {
box-shadow: 0 0 4px #000;
}
4.9.2. Mixins without parameters
A mixin can also group declarations without taking any parameters.
@mixin flexbox-center {
display: flex;
justify-content: center;
align-items: center;
}
Use in any rule that needs this centering behavior:
include
.header {
@include flexbox-center;
}
4.10. The legacy
import directive
Older Sass projects use to combine files. Sass has deprecated importing Sass files this way. Use
import
use and
forward for new modules.
- Organize source files: Split styles into partials for areas such as variables, mixins, headings, and buttons.
- Legacy entry point: A main file such as
styles.scsscan import individual Sass files. A directory can be referenced when it provides a resolvable index file.
Sass can resolve partial names without the leading underscore or extension, as in these examples:
// Import one Sass file (the .scss extension is optional) @import '_colors'; // Import one Sass file @import 'scss/_colors.scss'; // Import multiple files @import 'scss/_colors.scss', 'scss/_layout.scsss; // Import one CSS file @import 'footer.css'; // Wildcard imports require an additional build tool @import 'scss/*';
- Compile: Compile the entry point to produce the final CSS output.
sass styles.scss styles.css
4.11. The
extend directive
Use to make one selector match where another selector is used. Sass updates the relevant selectors in the generated CSS.
extend
Basic syntax:
selector-a {
property: value;
}
selector-b {
@extend selector-a;
/* More rules for selector-b */
}
Here, selectors A and B share the declarations. Use this when they genuinely represent the same kind of component.
For example, the primary and secondary button variants can extend a common button selector so their base styles stay consistent.
.button {
padding: 10px 20px;
background-color: #3498db;
color: #ffffff;
text-decoration: none;
}
.primary-button {
@extend .button;
background-color: #e74c3c;
}
.secondary-button {
@extend .button;
background-color: #27ae60;
}
4.12. Arithmetic operators
Sass calculates numeric values at compile time. Prefer math.div() for division in SCSS. Slash remains meaningful in CSS syntax.
| Operator | Description | Example |
|---|---|---|
| + | Addition | $ancho: 100px + 50px; |
| – | Subtraction | $padding: 20px - 10px; |
| * | Multiplication | $columnas: 3 * 4; |
| / | Division | $ancho-total: math.div(300px, 2); |
| % | Remainder | $resto: 9 % 4; |
- Addition (+): Adds compatible values.
$ancho: 100px + 50px; // Result: $ancho = 150px
- Subtraction (−): Subtracts compatible values.
$padding: 20px - 10px; // Result: $padding = 10px
- Multiplication (*): Multiplies values.
$columnas: 3 * 4; // Result: $columnas = 12
- Division: Use
math.div()for Sass arithmetic.
@use "sass:math"; $ancho-total: math.div(300px, 2); // Result: $ancho-total = 150px
- Remainder (%): Returns the remainder of a division.
$resto: 9 % 4; // Result: $resto = 1
5. Compiling Sass
Compile Sass from the command line, an editor, or a task runner. The following examples use the Sass command-line tool.
Prerequisite: Install Sass as shown in section 3.
5.1. Compile Sass from the command line
Open a command prompt or terminal. Use cd to move to the directory that contains your files.
cd path/to/project
5.1.1. Compile a single file
Run sass with the input and output filenames. The example uses estilos.scss and estilos.css.
sass estilos.scss estilos.css
This compiles the source file to CSS in the same directory.
5.1.2. Watch for changes
Add --watch to recompile as you edit the Sass source:
sass --watch estilos.scss estilos.css
Sass watches the source and regenerates the CSS when it changes. Link the generated CSS from your HTML.
5.1.3. Compile multiple files
Use input-output pairs to compile several entry points in one command:
sass light.scss:light.css dark.scss:dark.css
To compile a whole source directory, pass an input directory and a separate output directory:
sass src:public/css
5.1.4. Compile compressed CSS
Use --style=compressed to remove unnecessary whitespace. A .min.css suffix can make the generated file easier to recognize.
sass --style=compressed archivo1.scss archivo1.min.css
5.1.5. Sass command reference
| Purpose | Command |
|---|---|
| Compile one file | sass archivo.scss archivo.css |
| Watch for changes | sass –watch archivo.scss archivo.css |
| Compile multiple files or a directory | sass archivo1.scss:archivo1.css archivo2.scss:archivo2.css archivoN.scss:archivoN.css sass ./ |
| Compile compressed CSS | sass –style=compressed archivo.scss archivo.min.css |
5.1.6. A complete Sass file and its output
This example combines variables, nesting, comments, lists, and maps.
exercise.scss
// Variables
$color-primario: #3498db;
$color-secundario: #e74c3c;
$color-terciario: #2ecc71;
$tamano-fuente: 16px;
$espaciado: 20px;
// Map of button styles
$estilos-botones: (
default: (
fondo: $color-primario,
color-texto: white,
),
secundario: (
fondo: $color-secundario,
color-texto: white,
),
exitoso: (
fondo: $color-terciario,
color-texto: white,
),
);
// Styles
.contenedor {
padding: $espaciado;
background-color: #f0f0f0;
h1 {
font-size: $tamano-fuente;
color: $color-primario;
}
ul {
list-style: none;
li {
margin-bottom: 10px;
}
}
}
.boton {
display: inline-block;
padding: 10px 20px;
border: 1px solid transparent;
border-radius: 5px;
cursor: pointer;
&.default {
background-color: map-get($estilos-botones, default, fondo);
color: map-get($estilos-botones, default, color-texto);
}
&.secundario {
background-color: map-get($estilos-botones, secundario, fondo);
color: map-get($estilos-botones, secundario, color-texto);
}
&.exitoso {
background-color: map-get($estilos-botones, exitoso, fondo);
color: map-get($estilos-botones, exitoso, color-texto);
}
&:hover {
border-color: darken(map-get($estilos-botones, default, fondo), 10%);
}
}
In this example:
- Variables store colors, font sizes, and spacing.
- The
$estilos-botonesmap stores button variants. - The container rule nests styles for a heading and list.
- Button variants use values from the map for classes such as
.default,.secundario, and.exitoso. - The example uses the legacy functions
map-get()anddarken(). Their modern module counterparts let you read the map and adjust the hover color.
Run this command to compile the source:
sass exercise.scss exercise.css
Add --watch when you want recompilation after each edit:

The compiled CSS looks like this:
exercise.css
.contenedor {
padding: 20px;
background-color: #f0f0f0;
}
.contenedor h1 {
font-size: 16px;
color: #3498db;
}
.contenedor ul {
list-style: none;
}
.contenedor ul li {
margin-bottom: 10px;
}
.boton {
display: inline-block;
padding: 10px 20px;
border: 1px solid transparent;
border-radius: 5px;
cursor: pointer;
}
.boton.default {
background-color: #3498db;
color: white;
}
.boton.secundario {
background-color: #e74c3c;
color: white;
}
.boton.exitoso {
background-color: #2ecc71;
color: white;
}
.boton:hover {
border-color: #217dbb;
}
/*# sourceMappingURL=exercise.css.map */
5.2. Compile Sass in an online editor
Online editors let you write Sass and inspect the compiled CSS or preview a page. Examples include:
- SassMeister: Enter Sass and inspect the generated CSS.

- CodePen: Select Sass or SCSS as the CSS preprocessor for a Pen and preview the page with your markup.
6. Recommendations for working with Sass
- Learn the fundamentals: Understand variables, nesting, and style rules before using more advanced features.
- Organize source files: Group related styles into partials such as
_variables.scss,_buttons.scss, and_headings.scss. Load them through an entry point or modules. - Use variables for shared values: Keep a consistent set of colors, font sizes, and spacing values for the site.
- Keep nesting shallow: Long selectors can increase specificity and tie the stylesheet too closely to the markup.
- Document decisions: Add comments to explain why an approach was chosen or how a component is intended to be reused.
- Use functions where they simplify the code: A function works best when it expresses a calculation you need repeatedly.
- Test and use version control: Check the compiled styles in target browsers and use Git or another version-control system to track the sources.
- Maintain your tools: Keep a supported Sass version and test changes to compilers or build tools before relying on them.
- Explore packages when useful: Choose extensions or libraries that fit the project and check how they are maintained.
- Keep learning: Follow Sass changes and update legacy code when you have an opportunity to test it.
See Sass Guidelines and the official Sass documentation.
7. Worked Sass exercises
Try the exercises before comparing your work with the solutions.
7.1. Button variants in different colors
Create styles.scss with styles for buttons in different colors. Store the colors in variables and a map. Use nesting and & to define styles for individual variants.
Solution (index.html):
<button class="button primary">Primary button</button> <button class="button success">Success button</button> <button class="button danger">Danger button</button>
Solution (styles.scss):
// Define the button colors
$primary-color: #3498db;
$success-color: #27ae60;
$danger-color: #e74c3c;
// Define a map of button styles
$button-styles: (
primary: (
background-color: $primary-color,
color: white,
),
success: (
background-color: $success-color,
color: white,
),
danger: (
background-color: $danger-color,
color: white,
),
);
// Base button styles
.button {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
margin: 5px;
transition: background-color 0.3s ease;
&:hover {
background-color: darken($primary-color, 10%);
}
}
// Styles for each button variant
@each $button, $style in $button-styles {
.#{$button} {
background-color: map-get($style, background-color);
color: map-get($style, color);
&:hover {
background-color: darken(map-get($style, background-color), 10%);
}
}
}
Compiled CSS in CodePen:
7.2. Colored boxes with control flow
Create styles.scss and use to generate boxes with different background colors. Darken each background on hover. The original solution uses
fordarken().
Solution (index.html):
<div class="caja caja-1"></div> <div class="caja caja-2"></div> <div class="caja caja-3"></div> <div class="caja caja-4"></div> <div class="caja caja-5"></div> <div class="caja caja-6"></div> <div class="caja caja-7"></div> <div class="caja caja-8"></div> <div class="caja caja-9"></div> <div class="caja caja-10"></div>
Solution (styles.scss):
// Set how many boxes to create
$num-cajas: 10;
// Define a list of background colors
$colores-fondo: #3498db, #27ae60, #e74c3c, #9b59b6, #f1c40f, #2ecc71, #e67e22, #1abc9c, #34495e, #d35400;
// Set the size of each box
$tamano-caja: 100px;
// Base box styles
.caja {
width: $tamano-caja;
height: $tamano-caja;
margin: 10px;
display: inline-block;
}
// Generate the boxes with a @for loop
@for $i from 1 through $num-cajas {
$color-fondo: nth($colores-fondo, $i); // Get a background color from the list
.caja-#{$i} {
background-color: $color-fondo;
// Darken the background on hover
&:hover {
background-color: darken($color-fondo, 10%);
}
}
}
7.3. My online shop
Write styles.scss to match the visual reference and follow the requirements below. Keep the starter HTML as supplied.
Starter HTML:
<h1>My online shop</h1> <p>Explore our products and offers.</p> <button class="primary-button">View products</button> <button class="secondary-button">Register</button> <h2>Featured products</h2> <div class="product"> <img src="https://cdn-icons-png.flaticon.com/128/4990/4990734.png" alt="Prod 1"> <h3>Product 1</h3> <p>Description of product 1.</p> <p class="important-text">$19.99</p> <button class="buy-button">Buy</button> </div> <div class="product"> <img src="https://cdn-icons-png.flaticon.com/128/4990/4990734.png" alt="Prod 2"> <h3>Product 2</h3> <p>Description of product 2.</p> <p class="important-text">$24.99</p> <button class="buy-button">Buy</button> </div> <div class="product centered"> <img src="https://cdn-icons-png.flaticon.com/128/4990/4990734.png" alt="Prod 3"> <h3>Product 3</h3> <p>Description of product 3.</p> <p class="important-text">$29.99</p> <button class="buy-button">Buy</button> </div>
Visual reference:

Requirements:
- Create a file named
styles.scss. - Define the following variables:
$primary-color: #3498db$secondary-color: #e74c3c$font-family: Arial$base-font-size: 16px
- Apply these styles:
- Body: Set the background to
#f2f2f2, use$font-family, and center the text. - h1: Use a 2rem font size and
$primary-color. - Paragraphs: Set the font size to
1.2remand the color to#555. - Buttons: Use 10px vertical and 20px horizontal padding, no border, a 5px radius, a 10px margin, and a 0.3-second background-color transition.
- .product: Use a white background, a solid 1px border, a 5px radius, a 10px margin, and a subtle shadow on hover.
- Product images: Use a maximum width of 100% and automatic height.
- h3: Set the product title size to
1.5rem. - .important-text: Make the product price bold and use
$secondary-color.
- Define a
$button-stylesmap with these keys and values:primary-button→$primary-colorsecondary-button→#2ecc71buy-button→#f39c12
- Create a
center-elementmixin that centers items in both directions. You may use Flexbox. - Use
to create the three button classes from the map. Give each its mapped background color and darken it by 10 percentage points on hover.
each - Create a
.centeredclass for the final product and apply the centering mixin with.
include
Solution (styles.scss):
$primary-color: #3498db; // Light blue
$secondary-color: #e74c3c; // Red
$font-family: 'Arial', sans-serif;
$base-font-size: 16px;
body {
background-color: #f2f2f2; // Light gray background
font-family: $font-family;
margin: 0;
padding: 0;
text-align: center;
}
h1 {
font-size: 2rem;
color: $primary-color;
margin-top: 20px;
}
p {
font-size: 1.2rem;
color: #555; // Dark gray
}
button {
padding: 10px 20px;
border: none;
border-radius: 5px;
margin: 10px;
color: white;
transition: background-color 0.3s ease;
}
.product {
background-color: white;
border: 1px solid #ddd;
border-radius: 5px;
padding: 20px;
margin: 10px;
transition: transform 0.2s ease;
img {
max-width: 100%;
height: auto;
}
h3 {
font-size: 1.5rem;
}
p {
font-size: 1rem;
color: #777;
}
.important-text {
font-weight: bold;
color: $secondary-color;
font-size: 1.2rem;
margin-top: 10px;
}
}
// Define a map of button styles
$button-styles: (
primary-button: $primary-color,
secondary-button: #2ecc71, // Emerald green
buy-button: #f39c12, // Orange-yellow
);
// Define a centering mixin
@mixin center-element {
display: flex;
justify-content: center;
align-items: center;
}
// Use @each to iterate over $button-styles
@each $button-styles, $color in $button-styles {
.#{$button-styles} {
background-color: $color;
&:hover {
background-color: darken($color, 10%);
}
}
}
//Include the mixin
.centered {
@include center-element;
}