Fundumentals
SASS Fundamentals: Getting Started
SASS (Syntactically Awesome Style Sheets) is a popular CSS preprocessor that adds power and elegance to basic CSS. It helps write maintainable, DRY (Don't Repeat Yourself) code that compiles into standard CSS for browsers.
Core Concepts
-
Preprocessing:
- You write code in a SASS syntax (SCSS or the older indented Sass syntax).
- A SASS compiler processes this code.
- Output: Standard CSS file that browsers can understand.
graph LR A[Write SCSS/Sass Code] --> B(SASS Compiler); B --> C[Generate Standard CSS]; C --> D{Browser Renders Styles}; -
Variables:
- Store reusable values like colors, fonts, or spacing units.
- Syntax: Use the
$
symbol followed by the variable name. - Benefit: Easy updates – change the value in one place, and it reflects everywhere.
Example:
// Define variables $primary-color: #3498db; $base-font-size: 16px; // Use variables body { font-size: $base-font-size; color: $primary-color; } .button { background-color: $primary-color; font-size: $base-font-size * 0.9; // Use operators }
-
Nesting:
- Mimic the structure of your HTML by nesting CSS selectors.
- Benefit: Improves readability and organization by grouping related styles.
Example:
// SCSS with Nesting nav { ul { margin: 0; padding: 0; list-style: none; li { display: inline-block; a { text-decoration: none; color: $primary-color; // Using variable from above &:hover { // Use '&' to reference the parent selector text-decoration: underline; } } } } }
Compiled CSS Output:
nav ul { margin: 0; padding: 0; list-style: none; } nav ul li { display: inline-block; } nav ul li a { text-decoration: none; color: #3498db; } nav ul li a:hover { text-decoration: underline; }
Getting Started Checklist
- Install a SASS compiler (e.g., Dart Sass via npm:
npm install -g sass
). - Create an SCSS file (e.g.,
styles.scss
). - Write your styles using SASS features.
- Compile your SCSS file to CSS:
sass styles.scss styles.css
. - Link the compiled
styles.css
file in your HTML.
Backlinks