Sass Ampersand Nesting with Pseudo Selectors

Last Updated : 27 Sep, 2024

Sass (Syntactically Awesome Style Sheets) is a powerful CSS preprocessor that extends CSS with features like variables, nested rules, and mixins. By using ampersand nesting, developers can create cleaner and more organized styles, especially when working with pseudo-selectors and complex selectors. This approach enhances maintainability and readability, making it easier to manage styles in larger projects. With Sass, you can streamline your CSS workflow and take full advantage of its advanced features.

Steps to use Sass Ampersand nesting with pseudo selectors

Step 1: Install Sass

  • You can use Dart Sass, which you can install via npm:
  • First, make sure you have Node.js installed. Then, navigate to your project folder and run:
npm init -y
npm install sass --save-dev

Project Structure:

file
Project Structure

Update dependencies:

{
"name": "my-sass-project",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"sass": "^1.79.3"
}
}

Step 3: Write Your Sass

In styles/main.scss, add your styles using ampersand nesting and pseudo-selectors:

CSS
.button {
    background-color: blue;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;

    &:hover {
        background-color: darkblue;
    }

    &:focus {
        outline: 2px solid lightblue;
    }

    &.primary {
        background-color: green;

        &:hover {
            background-color: darkgreen;
        }
    }
}

Step 4: Compile Your Sass

You need to compile your Sass to CSS. You can do this manually using the command line:

npx sass styles/main.scss styles/main.css

Step 5: Create Your HTML File

In index.html, link to the generated CSS file:

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
"width=device-width, initial-scale=1.0">
    <title>Sass Example</title>
    <link rel="stylesheet" href="styles/main.css">
</head>

<body>
    <h1>Hello, Sass!</h1>
    <button class="button">Click me</button>
    <button class="button primary">Primary Button</button>
</body>

</html>

Step 6: Watch for Changes (Optional)

  • To automatically compile your Sass whenever you make changes, you can use the --watch flag:
npx sass --watch styles/main.scss:styles/main.css

Step 7: Open Your HTML File

  • Open index.html in your browser. You should see the buttons styled according to your Sass rules, with the hover effects working as intended.
file
Output
Comment