Parent selector is a special type of selector in SASS, which allows us to reuse the outer(Parent) selector in an efficient way. See the example below to get the idea:
For example: Suppose we have following CSS style block,
a {
text-decoration: none;
display: inline-block;
background-color: lightgray;
}
Now, You want to add hover effect to the anchor block, then you will write
a:hover {
background-color: gray;
}
Using SASS you need not repeat the outer selector(a), either you can do the following:
SASS file:
a {
text-decoration: none;
display: inline-block;
background-color: lightgray;
&:hover {
background-color: gray;
}
}
Here & is called parent selector. Compiled CSS file will be same as our CSS style.
Compiled CSS file:
a {
text-decoration: none;
display: inline-block;
background-color: lightgray;
}
a:hover {
background-color: gray;
}
Advantages:
-
You can create new classes with prefix or suffix as the name of the parent selector, which enables us to write
very structured CSS styling, very efficiently.SCSS file:
.main-block { border: 1px solid black; position: relative; &_subblock1 { position: absolute; display: block; } &_subblock2 { position: absolute; display: inline-block; } }Compiled CSS file:
.main-block { border: 1px solid black; position: relative; } .main-block_subblock1 { position: absolute; display: block; } .main-block_subblock2 { position: absolute; display: inline-block; } -
You can use different pseudo-classes or pseudo-elements to add styles in outer(parent) selector. See in the
first example we have used :hover pseudo-class to add effect in anchor tag with parent selector.
Recommended Posts:
- SASS | Selector Functions
- Last-child and last-of-type selector in SASS
- jQuery | :parent Selector
- jQuery | parent > child Selector
- jQuery | parent descendant Selector
- Sass sass:list Module
- Sass sass:color Module
- Sass | sass:map module
- SASS | @if and @else
- CSS Preprocessor | SASS
- How to import SASS through npm ?
- SASS | Comments
- Sass | At-rules
- SASS | Variables
- SASS | Introduction
- SASS | @import
- Sass @each Rule
- SASS | Interpolation
- SASS | Operators
- SASS | Map Functions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

