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 a 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 prefixes or suffixes 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 the outer(parent) selector. See in the first example we have used :hover pseudo-class to add effect in an anchor tag with the parent selector.