Gagan Gagan - 4 months ago 11
CSS Question

How to re-use common css rules in css( sass )

I have a CSS stylesheet as below

.icon1 {
&:after {
content:"";
float: right;
width: 8px;
height: 8px;
border-radius: 100%;
background-color: #4ac102;
display: block;
position: relative;
}
}

.icon2 {
&:after {
content:"";
float: right;
width: 8px;
height: 8px;
border-radius: 100%;
background-color: #f1342f;
display: block;
position: relative;
}
}

.icon3 {
&:after {
content:"";
float: right;
width: 8px;
height: 8px;
border-radius: 100%;
background-color: #616a83;
display: block;
position: relative;
}
}


As you can see except for the background-color all the other properties are the same. Can I refactor this code in order to make it DRY?

Answer

You can use Extend/Inheritance for this:

  .icons {
    content:"";
    float: right;
    width: 8px;
    height: 8px;
    border-radius: 100%;      
    display: block;       
    position: relative;
  }

  .icon1 {
    &:after {
      @extend .icons;             
      background-color: #4ac102;
    }
  }
  .icon2 {
    &:after {
      @extend .icons;             
      background-color: #f1342f;
    }
  }

  .icon3 {
    &:after {
      @extend .icons;             
      background-color: #616a83;
    }
  }
Comments