- Instant help with your CSS coding problems

Use Sass Nesting with multiple classes

Question:
How to use Sass Nesting with multiple classes?
Answer:
.main-btn {
    display: flex;
    padding: 4px 20px;
    background: #66aaff;

    .icon {
        color: #fff;
    }

    &.active {
        background-color: #2244aa;
    }

    &:hover {
        font-weight: bold;
    }
}
Description:

Using the Sass precompiler has many advantages over plain CSS. One such advantage is the ability to nest multiple classes. Nesting allows you to improve the readability and transparency of your code. In addition, you need to write fewer lines of code and it helps improve specificity.

Let's see a basic HTML to demonstrate:

<div class="main-btn active">Btn <span class="icon">*</span></div>


The three most common nesting types are:

  • Child element style definition:
    .main-btn {
        display: flex;
        padding: 4px 20px;
        background: #66aaff;
    
        .icon {
            color: #fff;
        }
    }​
  • Define sibling style class:
    .main-btn {
        display: flex;
        padding: 4px 20px;
        background: #66aaff;
    
        &.active {
            background-color: #2244aa;
        }
    ​


  • Pseudo selector class style definition:
    .main-btn {
        display: flex;
        padding: 4px 20px;
        background: #66aaff;
    
        &:hover {
            font-weight: bold;
        }
    }​

The complete SCSS code is:

.main-btn {
    display: flex;
    padding: 4px 20px;
    background: #66aaff;

    .icon {
        color: #fff;
    }

    &.active {
        background-color: #2244aa;
    }

    &:hover {
        font-weight: bold;
    }
}

And the compiler generates the following plain CSS:

.main-btn {
  display: flex;
  padding: 4px 20px;
  background: #66aaff;
}
.main-btn .icon {
  color: #fff;
}
.main-btn.active {
  background-color: #2244aa;
}
.main-btn:hover {
  font-weight: bold;
}
Share "How to use Sass Nesting with multiple classes?"
Tags:
sass, nesting, multiple, classes, compound, selector, pseudo, scss
Technical term:
Use Sass Nesting with multiple classes
Interesting things
OpanAi's ChatGPT