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.
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.Compiled CSS:
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: