Alter LESS Mixin when body class is present?

2019-07-30 06:32发布

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条回答
放荡不羁爱自由
2楼-- · 2019-07-30 06:47

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()
}
查看更多
登录 后发表回答