Alter LESS Mixin when body class is present?

独自空忆成欢 提交于 2020-01-05 08:32:12

问题


I have a LESS mixin. When a certain body class is present I want to alter one value of the mixin.

.my-style() {
  font-weight: bold;
  color: red;
}

.my-style-altered() {
  color: blue;
}

.element {
  .my-style;
}

.body-class .element {
  .my-style-altered;
}

This is working fine. However my list of selectors is getting longer:

.my-style() {
  font-weight: bold;
  color: red;
}

.my-style-altered() {
  color: blue;
}

.element,
.element-2,
.element-3 {
  .my-style;
}

.body-class .element, 
.body-class .element-2,
.body-class .element-3 {
  .my-style-altered;
}

Is there a smarter way of writing my list of selectors so I dont have to repeat them twice? Ideally I would write them once, and for all of them my-style-altered() would be also applied if .body-class is present.


回答1:


Method 1: (Using different mixins for the base version and the body-class specific version)

Yes, you could avoid having to write all the selectors multiple times by nesting the .body-class * variants of the selector within the generic one and appending the parent selector like in the below snippet. When this code is compiled, Less compiler will automatically replace the & with each one of the parent selectors.

.my-style() {
  font-weight: bold;
  color: red;
}

.my-style-altered() {
  color: blue;
}

.element, .element-2, .element-3 {
  .my-style;
  .body-class &{
      .my-style-altered;
  }
}

Compiled CSS:

.element, .element-2, .element-3 {
  font-weight: bold;
  color: red;
}
.body-class .element,
.body-class .element-2,
.body-class .element-3 {
  color: blue;
}

Method 2: (Using same mixin for the base version and the body-class specific version)

Alternately, if you wish to avoid having to use two different mixins and output both the content (the default one and the .body-class * variant) through the same mixin, it can be done like below:

.mixin() {
  font-weight: bold;
  color: red;
    .body-class &{
        color: blue;
    }
}

.element, .element-2 {
  .mixin()
}


来源:https://stackoverflow.com/questions/28606726/alter-less-mixin-when-body-class-is-present

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!