LessCSS unitless mixins

When doing development and you need to dimensions to a block element in CSS its pretty tedious to write:


.block {
width: 200px;
height: 200px;
}

I use LessCSS as my css pre-processor so wrote a handy little mixin to shorten this:


.size(@w, @h) {
width: @w;
height: @h;
}

Then to use it in the example above I would use:


.block {
.size(200px,200px);
}

Not much of a saving but when you do this 20-30 times in a less file the savings can add up. One thing that always bugged me though was that I had to pass through the px in the mixin arguments. I thought the way to get round this would be to change the mixin code to:


.size(@w, @h) {
width: @{w}px;
height: @{h}px;
}

However this always resulted in a syntax error. I guess the variable interpolation isn’t that great. I have however solved this today to achieve the simpler .size(200,200) that I am after use this funky syntax:


.size(@w, @h) {
width: ~"@{w}px";
height: ~"@{h}px";
}

Lovely jubbly or to extend it further in case you want to throw in a different unit but default to pixels:


.size(@w, @h, @unit: 'px') {
width: ~"@{w}@{unit}";
height: ~"@{h}@{unit}";
}

Leave a Reply

Your email address will not be published. Required fields are marked *