Sub topic 3
Loops, Modules, and Sass Project Structure
Assume you know CSS selectors, media queries, and basic command-line use. Sass control rules help you generate repeated CSS while keeping source files organized.
Loops and conditionals
@each visits every item in a list or map. @if includes declarations only when a condition is true.
@use "sass:map";
$colors: (
primary: #3366cc,
danger: #cc3333
);
@each $name, $color in $colors {
.text-#{$name} {
color: $color;
}
@if $name == danger {
.text-#{$name} {
font-weight: 700;
}
}
}#{$name} is interpolation. It inserts a Sass value into a selector. Sass generates .text-primary and .text-danger.
Use loops for repeated, predictable output. Avoid generating large numbers of classes that the application does not need.
`@extend` and placeholders
A placeholder selector begins with %. It contributes no CSS rule by itself. @extend shares its declarations with another selector.
%button-base {
padding: 0.5rem 1rem;
border-radius: 4px;
}
.button-primary {
@extend %button-base;
background: #3366cc;
}Use @extend for closely related selectors. Prefer a mixin when you need configurable declarations or when selectors come from unrelated components. Excessive extension can create surprising combined selectors.
Partials and modules
A partial is a Sass file whose name starts with _, such as _tokens.scss. Load it with @use, which gives its members a namespace. Use @forward to expose members through a public entry point.
// _tokens.scss
$space: 8px;
// _theme.scss
@forward "tokens";
// main.scss
@use "theme";
.card {
padding: theme.$space * 2;
}@use loads a module once and prevents accidental global variables. New code should use it instead of deprecated @import.
Built-in modules
Built-in modules provide namespaced functions. For example, sass:math makes arithmetic explicit, and sass:map reads map values.
@use "sass:map";
@use "sass:math";
$scale: (small: 8px, large: 24px);
.panel {
padding: math.div(map.get($scale, large), 2);
}Organizing and migrating
A small project might use this structure:
styles/
_tokens.scss
_mixins.scss
_components.scss
main.scssLet main.scss be the entry point. Keep tokens, reusable mixins, and component rules in separate modules. Replace each @import "file"; with @use "file";, then qualify variables and mixins with the module namespace.
Exercise
When should you prefer a mixin over @extend?
Show answer
Prefer a mixin when declarations need arguments or when the selectors are not tightly related.