@viewport, @media and LESS

2019-04-29 15:26发布

I've recently converted some CSS to LESS for use with a .NET application (I am using dotless for .NET, http://www.dotlesscss.org/ to compile the LESS at runtime).

The compiler is falling down on these two blocks of code:

@viewport {
  width: device-width;
}
/* Add a min-width for IE 8 and lower */
@media \0screen\,screen\9 {
    body {
        min-width: 960px;
    }
}

Just for your reference, the media query above is a hacky way of targeting IE

How can I "LESS-ify" these blocks of code?

1条回答
We Are One
2楼-- · 2019-04-29 15:30

In Less >= 1.4.0 you can simply define a variable and use it in the media query:

@iehack: \0screen\,screen\9;

@media @iehack {
    body {
        min-width: 960px;
    }
}

In older versions of LESS (<=1.3.3) you might want to use string string interpolation in the variable:

@iehack: ~'\0screen\,screen\9';

This should give you your desired output.

But if you want to go a hacky way in CSS you can as well go a hacky way in LESS too:

@themedia: ~"@media \0screen\,screen\9 {";
@aftermedia: ~"} after";
@{themedia} {
    body {
        min-width: 960px;
    }
}
@{aftermedia}{/*just to add the closing bracket to media*/}

where you inject the media query around a normal role, this generates an extra selector at the end of the media block, but you can use it for something useful as well, this technique might be used in more exciting instances than media queries ... but I just wanted to mention it.

In this case the CSS output would look like:

@media \0screen\,screen\9 { 
body {
  min-width: 960px;
}
}
after {
  /*just to add the closing bracket to media*/
}
查看更多
登录 后发表回答