首页 > 解决方案 > 如何在less中添加通用样式以及基于动态类添加不同样式

问题描述

下面是我有一个公共类的 HTML 签名,我想将相同的颜色属性应用于两个 div 元素。但是基于动态添加的背景类,我想为其添加背景颜色。尽管给定的 LESS 样式有效,但我试图重构不起作用的代码。

HTML:
<div class="common background-red"></div>
<div class="common background-warning"></div>

LESS: (which is working, please suggest if it can be refactored)
.background-red {
   color: blue;
   background-color: red;
}

.background-warning {
   color: blue;
   background-color: yellow;
}

我尝试了下面的代码,但它不工作

.common {
   color: blue
   .background-red {
     background-color: red;
   }
   .background-warning {
     background-color: yellow;
   }
}

标签: htmlcssless

解决方案


您可以使用 & 字符将一个类添加到一个类中,如下所示:

.common {
  color: blue
  &.background-red {
    background-color: red;
  }
  &.background-warning {
    background-color: yellow;
  }
}

可以在此处查看更多信息: https ://css-tricks.com/the-sass-ampersand/


推荐阅读