Question about less variables with media queries

In a site i’m developing atm i have been using lots of variables for width/height etc, thought this would make the responsive part easier and cleaner to handle. But I have a problem.

Lets do an example:

I have a div:

<div class="box"></div>

And the less/css:

@size: 100px;

.box{
width: @size;
height: @size;
}

Then I thought by just changing the variable in a media querie I could easily resize elements for different screen sizes, was I wrong?

When I try something like this it doesnt work I get “variable not defined” when I update the site in my browser.

@media only screen and (min-width: 768px) {
    @size: 100px;
}

@media only screen and (max-width: 767px) {
    @size: 50px;
}

.box{
width: @size;
height: @size;
}

Do i have to include the .box{} in every querie?

Hi,

I don’t use less but I know that’s its complied before use so you can’t have variables affecting anything once the page is complied because then it is plain css only.

The variables in your media query will only apply to content within that media query. If you don’t have matching rules in that media query then that variable is not applied.

You can test it out easily here.

It’s not the same but you can do something like this:


@smallscreen: ~"screen and (max-width: 479px)";
@mediumscreen: ~"screen and (min-width: 480px) and (max-width: 767px)";
@size:500px;

.box {
width: @size;
height: @size;
@media @smallscreen { width:50px;height: 50px }
@media @mediumscreen {  width:350px;height: 350px }
}

Which will compile to this:


.box {
  width: 500px;
  height: 500px;
}
@media screen and (max-width: 479px) {
  .box {
    width: 50px;
    height: 50px;
  }
}
@media screen and (min-width: 480px) and (max-width: 767px) {
  .box {
    width: 350px;
    height: 350px;
  }
}