Search code examples
csslesslesscss-resources

Mixing in Less CSS


I'm still new at using Less CSS and I couldn't find a solution to my problem. I want a more efficient output result.

I have this code in less :

.btn-trans {
      color: inherit;
      background-color: transparent;
      transition: all .4s;

      &.btn-default {
        color: @trans-default;
        &:hover {
          color: @trans-hover-color;
        }
      }

      &.btn-primary {
        color: @trans-primary;
        &:hover {
          color: @trans-hover-color;
        }
     }
  }

And this is the css output :

.btn-trans {
  color: inherit;
  background-color: transparent;
  transition: all .4s;
}

.btn-trans.btn-default {
  color: #bdbdbd;
}

.btn-trans.btn-default:hover {
  color: #f5f5f5;
}

.btn-trans.btn-primary {
  color: #738ffe;
}

.btn-trans.btn-primary:hover {
  color: #f5f5f5;
}

But the result I'm looking for is this :

.btn-trans {
  color: inherit;
  background-color: transparent;
  transition: all .4s;
}

.btn-trans.btn-default {
  color: #bdbdbd;
}

.btn-trans.btn-primary {
  color: #738ffe;
}

.btn-trans.btn-default:hover,
.btn-trans.btn-primary:hover {
  color: #f5f5f5;
}

With the hover classes nested since the color is the same.


Solution

  • You can achieve this by using a class that is pretty much like grouping the selectors you want to use together.

    Snipet

    .custom-class(){
      .btn-trans.btn-default:hover,
        .btn-trans.btn-primary:hover {
        color: #f5f5f5;
        }
    }/*-- end of the custom class --*/
    .btn-trans {
          color: inherit;
          background-color: transparent;
          transition: all .4s;
    
          &.btn-default {
            color: #ccc;
    
            &:hover {
              color: #ccc;
            }
          }
    
          &.btn-primary {
            color: #ccc;
    
            &:hover {
              color: #ccc;
            }
         }
      }
    
    /*-- use of the custom class --*/
    .custom-class;
    

    or you can go for a nested approach by grouping on the upper level

    snipet

    .btn-trans {
      color: inherit;
      background-color: transparent;
      transition: all .4s;
    
      &.btn-default {
        color: #ccc;
      }
    
      &.btn-primary {
        color: #ccc;
      }
    
      &.btn-default,
      &.btn-primary {
        &:hover {
          color: #ccc;
        }
      }
    }