Reputation: 3262
I'm trying to understand how to get conditional statements to work for LESS. I have the following helper to assist in defining font styles. I would like the font-size
declaration to be optional.
.Gotham(@size: false) {
letter-spacing: 1px;
font-family: 'Gotham', Arial, sans-serif;
text-transform: uppercase;
& when (@size) {
// This doesn't seem to apply
color: red !important;
font-size: @size; // Need to append "px"
}
}
// I want to be able to use it like this:
H1 {
.Gotham(20);
}
P {
.Gotham();
}
Upvotes: 1
Views: 47
Reputation: 89780
In Less, any value other than true
is generally considered as falsy and so an input value of 20
will not match the & when (@size)
guard resulting in that block never getting executed.
The below lines are extracted from the official Less website:
Additionally, the keyword true is the only truthy value. Any value other than the keyword true is falsy
You need to modify your mixin code to be like provided below:
.Gotham(@size: false) {
letter-spacing: 1px;
font-family: 'Gotham', Arial, sans-serif;
text-transform: uppercase;
& when not (@size = false) {
color: red !important;
font-size: unit(@size, px);
}
}
H1 {
.Gotham(20);
}
P {
.Gotham();
}
Units can be appended to the numeric by using the built-in unit()
function. This function takes two input parameters where the first one is the number to which the unit has to be added and the second is the actually unit. Using this approach you can convert a number to em
or px
or rem
etc.
Another option that I've always liked as opposed to true or false comparison is to check whether the input value is of the required type or not. Here, since the input value is used for font-size
, it is valid only if it is a number and so, the guard can be written using the isnumber()
function also:
.Gotham(@size: false) {
letter-spacing: 1px;
font-family: 'Gotham', Arial, sans-serif;
text-transform: uppercase;
& when (isnumber(@size)) { /* enter only when input is a number, false isn't :) */
color: red !important;
font-size: unit(@size, px);
}
}
H1 {
.Gotham(20);
}
P {
.Gotham();
}
Upvotes: 1