CSS Preprocessors (SASS, LESS)

CSS preprocessors like SASS (Syntactically Awesome Stylesheets) and LESS (Leaner Style Sheets) enhance CSS by introducing variables, nesting, mixins, functions, and more. They improve code organization, reusability, and maintainability.

1. What are CSS Preprocessors?

A CSS preprocessor extends the functionality of regular CSS by allowing developers to use features like variables, functions, loops, and nesting. The preprocessor compiles the code into standard CSS.

2. SASS (Syntactically Awesome Stylesheets)

SASS is one of the most popular CSS preprocessors and has two syntax options:

  • SCSS (Sassy CSS): Uses a CSS-like syntax.
  • Indented SASS: Uses indentation instead of curly braces.

Example: Using Variables in SASS

// SASS Example
$primary-color: #3498db;

.button {
    background: $primary-color;
    color: white;
    padding: 10px;
}

Example: Nesting in SASS

.nav {
    background: #333;
    
    ul {
        list-style: none;
        padding: 0;
        
        li {
            display: inline-block;
            margin: 10px;
            
            a {
                color: white;
                text-decoration: none;
            }
        }
    }
}

Compiling SASS to CSS

# Install SASS
npm install -g sass

# Compile SASS to CSS
sass styles.scss styles.css

3. LESS (Leaner Style Sheets)

LESS is another CSS preprocessor that allows for **variables, nesting, and mixins**.

Example: Using Variables in LESS

@primary-color: #3498db;

.button {
    background: @primary-color;
    color: white;
    padding: 10px;
}

Example: Nesting in LESS

.nav {
    background: #333;
    
    ul {
        list-style: none;
        padding: 0;
        
        li {
            display: inline-block;
            margin: 10px;
            
            a {
                color: white;
                text-decoration: none;
            }
        }
    }
}

Compiling LESS to CSS

# Install LESS
npm install -g less

# Compile LESS to CSS
lessc styles.less styles.css

4. SASS vs. LESS: Key Differences

Feature SASS LESS
Syntax SCSS & Indented LESS (CSS-like)
Compilation Node.js, Ruby, Dart Node.js
Variables $variable @variable
Mixins Yes Yes

5. Which One Should You Use?

  • Use SASS if you need advanced features, flexibility, and a powerful CSS architecture.
  • Use LESS if you prefer a simpler, JavaScript-friendly approach.

Conclusion

CSS preprocessors like SASS and LESS help write cleaner and more maintainable CSS. By using variables, nesting, and mixins.