Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In LESS, is it possible to get image dimension from the bitmap files?

Tags:

less

I found myself hard-coding some image width numbers in my LESS stylesheet.

It is possible to have a LESS function automate this? e.g.

@banner-width : image-width("image/banner.png");
like image 488
Samphan Avatar asked Apr 20 '13 03:04

Samphan


1 Answers

If you are using a javascript implementation of less (less.js), you could use javascript interpolation between back-ticks and use normal javascript functionality - something like this:

@banner-width: ~`function(imguri){var img=new Image(); img.src = imguri; return img.width }('image/banner.png')`;

or go further and make reusable mixins.

LESS:

.width(@img) {
  @width: ~`function(imguri){var img=new Image(); img.src = imguri; return img.width }(@{img})`;
    width: @width;
}
.height(@img) {
  @height: ~`function(imguri){var img=new Image(); img.src = imguri; return img.height }(@{img})`;
    height: @height;
}

.test{
    @src: 'http://www.google.com/intl/en_ALL/images/logo.gif';
    .width(@src);
    .height(@src);
}

the output CSS:

.test {
  width: 276;
  height: 110;
}

which is exactly what it should be for this logo http://www.google.com/intl/en_ALL/images/logo.gif

  • to add the units you coud then add unit(@dimension,px) into the mixins.
like image 185
Martin Turjak Avatar answered Jan 02 '23 20:01

Martin Turjak