How to convert a number in Less code into a valid CSS measuring unit

When working with less you most probably have to do some calculations and assign their result in a CSS property, for example into a width of a CSS class or a margin of an CSS id.

Apart from the calculated number you want to generate valid CSS code, so you also have to apply a measuring unit to this number, for example pixels or ems or percentages.

Consider the following example:

1
2
3
    #someDiv {
        width: 20*5 + 50;
    }

This less example will generate the following CSS rule: width: 150;. However, this is not valid and the width will not apply to the id.

The solution is to apply the measuring unit you want on one of the number that take part in the calculation. For convenience I would suggest you to apply this unit at the last number in order to make it obvious for the other what exactly happens. Consider the following revised example:

1
2
3
    #someDiv {
        width: 20*5 + 50px;
    }

This will produce the following CSS rule: width: 150px;. The same would happen if instead of px you used em or %.

comments powered by Disqus