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.
/* nested property using parent selector */
/* this will be compiled as #someclass-body */
& 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,
/* Some HTML code */
As we have seen in the example above in nested rules, we can use Sass nested rules to define styling for
#studytonight-body, but Sass makes it further easier using the parent selector syntax.
/* styling for #studytonight div */
/* styling for #studytonight-body div */
& 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
: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,
// using parent selector
This is equivalent to the following CSS code,
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.