LESS CSS set variables in media query?
It would be nice, but this is impossible to do like this.
LESS compiles your media queries to actual media queries, so at compile time there is no indication of which media query will be relevant to the browser.
After compile time you just have CSS not less so you can't have variables anymore.
You can do this instead but it isn't as elegant:
@base_width: 100px;
@media all and (max-width: 768px) {
.something {
width: @base_width;
}
}
@media all and (min-width: 769px) {
.something {
width: @base_width * 2;
}
}
I know I'm late with my answer but someone may find this useful.
You can move your styles to a separate file
// styles.less
.foo {
width: 100px * @ratio;
}
And then import the file multiple times after changing variables' values
// main.less
@ratio: 1; // initial value
@media all and (max-width: 768px) {
@ratio: 1;
@import (multiple) "styles";
}
@media all and (min-width: 769px) {
@ratio: 2;
@import (multiple) "styles";
}
Note that (multiple) is important here
Compiled code will look like this
// main.css
@media all and (max-width: 768px) {
.foo {
width: 100px;
}
}
@media all and (min-width: 769px) {
.foo {
width: 200px;
}
}
For those who might allow supporting relatively modern browsers only (Chrome 49+, FF 31+, no IE), you can use css variables instead.
Here is browser support table from "Can I Use".
html {
--width-var: 300px;
@media only screen and (max-width: 750px) {
--width-var: 200px;
}
}
.your-class {
max-width: calc( var(--width-var) * 2 );
.... // tons of other props
}
With the code above, whenever screen is getting smaller than 750px, max-width
property from .your-class
is recalculated (since --width-var
is changed), and of course when screen is resized to be bigger - css variable gets back to its original value.