Sub topic 1
What Sass Is and Why Use It
Prerequisites
You should know CSS selectors, properties, the cascade, and media queries. You should also be comfortable with basic command-line commands, HTML, and linking a stylesheet.
What Sass Adds to CSS
Sass is a CSS preprocessor. It lets you write source code with features such as variables, nesting, and reusable functions. Dart Sass then compiles that source into ordinary CSS that browsers can read.
Sass does not run in the browser. The compiled CSS must be generated during development or as part of a build process.
Sass helps when a stylesheet has repeated values or complex selector relationships. It can also make a large stylesheet easier to split into files. The output is still CSS, so you must understand the CSS it generates.
Installing Dart Sass and Compiling Files
Install the Dart Sass command-line tool in a project:
npm install --save-dev sass
npx sass src/styles.scss dist/styles.css
npx sass --watch src:distThe first command adds Sass to the project. The second compiles one file. Watch mode recompiles files whenever a source file changes.
A common error is editing the .scss file while linking it directly in HTML. Link the generated .css file instead.
SCSS and Indented Syntax
SCSS is the common Sass syntax. It uses braces and semicolons, so valid CSS is also usually valid SCSS. Sass also has an indented syntax that uses indentation instead of braces and semicolons. Do not mix the two styles in one file.
Variables and Nesting
A Sass variable stores a reusable value. The $ prefix identifies a variable. Nesting places related selectors inside a parent selector. Use & when you need the exact parent selector.
$primary: #3366cc;
$radius: 4px;
.card {
border: 1px solid $primary;
border-radius: $radius;
&:hover {
background: rgba($primary, 0.1);
}
&__title {
font-weight: 700;
}
}This produces .card:hover and .card__title. Keep nesting shallow. Deep nesting creates selectors with high specificity and makes later overrides harder.
Exercise
What selector does &__title produce inside .card?
Show answer
It produces .card__title.