少混 CSS

Mixing in Less CSS

我对使用 Less CSS 还是个新手,我找不到解决问题的方法。 我想要更高效的输出结果。

我在 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;
        }
     }
  }

这是 css 输出:

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

但我正在寻找的结果是这样的:

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

悬停 类 嵌套,因为颜色相同。

生成 CSS 完全没问题,只是文件大小多了两行。

如果你真的想要你的输出,你可以试试这个:

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

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

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

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

您可以通过使用 class 来实现这一点,这非常类似于将要一起使用的选择器分组。

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;

或者您可以通过在上层分组来采用嵌套方法

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;
    }
  }
}

使用这个

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

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