SASS | Parent Selector

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:

  1. 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;
    }
    
            
  2. 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.


My Personal Notes arrow_drop_up

I am doing BTech at Dhirubhai Ambani Institute of Information and Communication Technology

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.