Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LESS variables in media queries

Tags:

css

less

When I enter the following less code: (paste it into http://less2css.org)

@item-width: 120px;
@num-cols: 3;
@margins: 2 * 20px;
@layout-max-width: @num-cols * @item-width + @margins;

@media (min-width: @layout-max-width) {
    .list {
      width: @layout-max-width;
    }
}

... the resulting CSS is:

@media (min-width: 3 * 120px + 40px) {
  .list {
    width: 400px;
  }
}

Notice that the same variable @layout-max-width - in the media query it produces an expression (which isn't what I want) and when used as the value for the width property it produces 400px (which is also what I want for the media query.)

Is there formal syntax in LESS which enables me to do this?

If not - is there a workaround?

like image 615
Danield Avatar asked Feb 12 '14 22:02

Danield


People also ask

Why you shouldn't use media queries?

Media queries are great for adapting layouts to various screen sizes, but terrible for creating modular designs. Modular CSS is already hard enough, and media queries provide very little to no help. Truly modular layouts need to respond to the sizes of containers, not just to the viewport's size.

Should I use MIN or MAX in media query?

At the basic level, media queries enable an email developer to create a responsive email by detecting the width of the display. For this purpose, the most commonly used query is max-width. Any width that is less than the max-width specified, all of the CSS within the query will take effect.


1 Answers

Due to Math Settings

LESS by default expects math operations to be in parenthesis (strict-math=on). So your variable needs those around the values to calculate correctly, like so:

@layout-max-width: (@num-cols * @item-width + @margins);

Then your original code will output as you expect.

like image 85
ScottS Avatar answered Sep 28 '22 16:09

ScottS