Search code examples
javascripthtmlcsslessretina-display

How to use a variable for image paths with less mixins


I'm new to Less and I'm trying to use http://retinajs.com/ to load retina images when possible.

The script has this mixin to use when calling images in your css:

.at2x(@path, @w: auto, @h: auto) {
  background-image: url(@path);
  @at2x_path: ~`"@{path}".split('.').slice(0, "@{path}".split('.').length - 1).join(".") + "@2x" + "." + "@{path}".split('.')["@{path}".split('.').length - 1]`;
  @media all and (-webkit-min-device-pixel-ratio : 1.5) {
    background-image: url(@at2x_path);
    background-size: @w @h;
  }  
}

My question, is if I'm using a variable for one of my images, how do I correctly use the variable to work in the mixin.

Doing something like this does not work:

  .at2x('@myImgPathVariable', 150px, 64px);

Nor does this:

  .at2x('("@{myImgPathVariable}/logo.png")', 150px, 64px);

Hope this makes sense, thanks.


Solution

  • Luke and Om are both on to something. How your variable is declared could make a big difference. Doing it this way seemed to work for me:

    @myImgPathVariable: ~'https://developers.google.com/images/developers-logo.png';
    
    div {
        .at2x(@myImgPathVariable, 200px, 48px);
    }
    

    Full example: http://jsfiddle.net/jstam/yUtxp/