& CSS




The Ampersand (&) itself is not a CSS feature. But it is a very useful feature in SCSS. SCSS is a preprocessor scripting language that is interpreted or compiled into CSS.


 The ampersand (&) is used while we need to nest the classes.

Basic Nesting in SCSS


    .outerClass{
        .innerClass{}
    }



The above example compiled to CSS and look like this


    .outerClass .innerClass{}



You can be nested even deeper but keep it simple it is best practice to make one level deep.

Multilevel nested SCSS:

   
    .outerClass{
        .innerClass{
            .innerOne{
                .deepInner{
                    
                }
            }
        }
    }


The output of the above example code

    .outerClass .innerClass .innerOne .deepInner {

    }
    

Nesting by using an ampersand (&)

- & is very important when creating more specific selecotor
- & refers to the parent selector in case of nesting.


        .outer-class {
            &.inner-class {color:#ddd}
        }
        


Output



    .outer-class.inner-class {
    color: #ddd;
    }



-& remove the code repetition


    .link {
        &:visited {  color: red; }
        &:hover {  color: red; }
        &:active {color:red; }
      }




After compiled to CSS


    .link:visited {
        color: red;
    }

    .link:hover {
        color: red;
    }

    .link:active {
        color: red;
    }







Reactions

Post a Comment

0 Comments