Skip to content
Related Articles

Related Articles

SASS | Parent Selector
  • Last Updated : 11 Oct, 2019

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
Recommended Articles
Page :