2

How to use LESS variables in @media queries in Adobe CQ5?

myFile.less:

@myVar = 10px;
span {
    width: @myVar;
}

works fine.

But:

myFile.less:

@myVar = 400px;
@media all and (min-width: @myVar) {
   span{ 
       color:red;
   }
}

Results with:

clientLib.css:

@media all and (min-width: @myVar) {
   span{ 
       color:red;
   }
}
tomalec
  • 890
  • 10
  • 27

2 Answers2

3

This code is perfectly valid LESS since version 1.2.0 (released two years ago):

@myVar: 400px;
@media all and (min-width: @myVar) {
   span { 
       color:red;
   }
}

So assuming @myVar = 400px; is just your typo here, it looks like you did not update your CQ5 for a while. Consider upgrading it to 5.6.1 which includes LESS v1.3.3 (pretty ancient too but at least it supports variables in media query).

I also suspect that it is possible to manually update LESS script included with the CQ simply by replacing the "less.js" file (found somewhere among other CQ files) by its newer version.

seven-phases-max
  • 11,765
  • 1
  • 45
  • 57
  • 2
    This works perfectly for fixed values. But just in case you want to do any math for the variable value, make sure to wrap it in parentheses, otherwise it won't work with media queries. E.g. `@myVar: (400px + @anotherVar);` – Nass Jan 27 '14 at 15:10
  • @Salmonface Try this again with the latest `less` version. If you put parentheses around your expression, this should work perfectly fine. I confirm that without parentheses it does not work at all. – Tomasz Lenarcik Apr 28 '14 at 10:49
0

From: http://flippinawesome.org/2013/05/20/less-tips-and-tricks/

/* note '~' in the beginning - media query must be escaped */
@singleQuery: ~"tablet and (min-width: 500px)";
@media screen, @singleQuery {
  set {
    padding: 3 3 3 3;
  }
}

--

@myVar: ~"400px";
@media all and (min-width: @myVar) {
   span{
       color:red;
   }
}

compiles to:

@media all and (min-width: 400px) {
  span {
    color: red;
  }
}
Bass Jobsen
  • 48,736
  • 16
  • 143
  • 224