Signup/Sign In

SASS Parent Selector - Using Ampersand

In SASS/SCSS syntax, we can use the & symbol(ampersand) to represent the parent class and define further nested rules. This ampersand(&) in SASS represents the parent selector and we can use it to write nested properties easily.

SASS Parent Selector Syntax:

The syntax for using the parent selector in a stylesheet in its nested selectors is very simple. All you have to do is use & (ampersand) as a prefix followed by some text and when you will compile the SCSS code into CSS code the ampersand sign will be replaced with the name of the parent selector.

#someclass {
    /* nested property using parent selector */
    &-body {
        /* this will be compiled as #someclass-body */
    }
}

The & sign should be at the beginning of the compound selector, but it can be followed by a suffix which is to be added to parent selector.

Using SASS/SCSS Parent Selector

Let's take an example to understand this. Consider the following HTML code,

<div id="studytonight">
    <div id="studytonight-body">
        /* Some HTML code */
    </div>
</div>

As we have seen in the example above in nested rules, we can use Sass nested rules to define styling for #studytonight and #studytonight-body, but Sass makes it further easier using the parent selector syntax.

#studytonight {
    /* styling for #studytonight div */
    &-body {
        /* styling for #studytonight-body div */
    }
}

The & symbol gets compiled to the parent selector value when the SCSS code is transpiled to CSS code. This comes in handy when we have to use pseudo-selectors like :hover, :selected etc with the main element. So if you have an anchor tag and you want to define styling for it for mouse hover, you can do so like this in Sass,

a {
    text-decoration: none;
    color:black;
    // using parent selector
    &:hover {
        color:red;
    }
}

This is equivalent to the following CSS code,

a{ 
    text-decoration: none;
    color:black;
}
a:hover
{
    color:red;
}

Conclusion:

Parent Selector is a small feature of SASS/SCSS but provides us with further simplified approach wherein one has to write less code with more meaning. This approach is significantly useful when we are writing styling code for nested HTML components like menus using lists or navbar etc.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight