Rick
Rick

Reputation: 259

How to interpolate a map value with string in Less

I can't seem to get my LESS mapping logic to work. I have followed the documentation on mapping.

@screen-size-min: {
  mobile-small: 320px;
  mobile-large: 480px;
  tablet-small: 600px;
  tablet-large: 768px;
  desktop-small: 992px;
  desktop-large: 1280px;
}

@min: min-width;

@desktop-small-min: ~"only screen and (@{min}: @screen-size-min[desktop-small])";

p {
  color: blue;

  @media @desktop-small-min {
    color: red;
  }
}

I'm expecting this code to compile to css, but the media query does not seem to compile.

p {
  color: blue;
}

@media only screen and (min-width: 992px) {
  p {
    color: red;
  }
}

I tried testing it on lesstester but it only supports LESS 2.7 at this time. Maps is a new feature in LESS 3.5

There are no compile errors. Where did I go wrong?

Upvotes: 2

Views: 337

Answers (2)

soulshined
soulshined

Reputation: 10592

This is happening because key[value] is not actually a variable, the variable is the map @screen-size-min, therefore you can not take advantage of variable interpolation. One solution is to simply concat the KVP with the rest of the string:

@desktop-small-min: ~"only screen and (@{min}:" @screen-size-min[desktop-small] ~ ")";

This eliminates any dependency on creating another variable just to interpolate it

Additionally, per their documentation, maps were introduced:

Released v3.5.0

And the online tester you tested with only supports 2.7

Codepen usually supports their latest versions. Here's an anonymous pen demonstrating:

https://codepen.io/anon/pen/zeXmev

If you click on the little down arrow next to the 'CSS (Less)' header, you can select 'View Compiled CSS' and it will show you the LESS -> CSS output

Upvotes: 4

Jakub Rusilko
Jakub Rusilko

Reputation: 867

This seems to be working:

@screen-size-min: {
  mobile-small: 320px;
  mobile-large: 480px;
  tablet-small: 600px;
  tablet-large: 768px;
  desktop-small: 992px;
  desktop-large: 1280px;
}

@min: min-width;
@mysize: @screen-size-min[desktop-small];

@desktop-small-min: ~"only screen and (@{min}: @{mysize})";

p {
  color: blue;

  @media @desktop-small-min {
    color: red;
  }
}

It produces the desired result. Try it here

Upvotes: 2

Related Questions