9

I'm trying to use LESS css to do the following:

width: ((480/1366)*100)+'%';

The problem though is that the output becomes:

width: 35.13909224011713 '%';

How do I make it workable? ie.:

width: 35.13909224011713%;
Harry
  • 87,580
  • 25
  • 202
  • 214
Joel
  • 181
  • 2
  • 5

3 Answers3

13

It is possible to use string interpolation:

@myvar: ((480/1366)*100);
width: ~"@{myvar}%";

That will output

width: 35.13909224011713%;

Additionally, if you want it to be rounded, you can use round().

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
ldiqual
  • 15,015
  • 6
  • 52
  • 90
  • Anyway I can do it without the var? I tried width: "@{(237/768)*100}%"; But it doesn't seem to work... – Joel Aug 08 '11 at 07:33
  • Hey, it's me again! Turns out it becomes a string when you do it like this. I need a number... i.e the end result is width: "35.13909224011713%"; So I'm afraid this won't work. – Joel Aug 08 '11 at 07:48
  • Turns out you also need to escape the string! So here's the correct solution with a ~ sign: @myvar: ((480/1366)*100); width: ~"@{myvar}%"; – Joel Aug 08 '11 at 07:54
  • Turns out you also need to escape the string! So here's the correct solution with a ~ sign: @myvar: ((480/1366)*100); width: ~"@{myvar}%"; – Joel Aug 08 '11 at 07:55
  • Well it worked without the `~` using less 1.1.3, but I edited my answer with it anyway. – ldiqual Aug 08 '11 at 09:05
  • The code ~"@{myvar}%" looks totally confusing for something so simple. I think this might be more easily readable: width: percentage((480 / 1366)); – Luke Apr 19 '13 at 20:25
8

Even though this question is quite old, I want to add a few more examples about adding. Less will set your units to whatever is being operated on.

10px + 20px

will output 30px

(20/200) * 100%

will output 10%

So with units you dont need to concatenate the unit measurement.

I have found that adding 0 helps when you dont know what the unit value might be.

.mixin(@x, @y){
    @result: (@x / @y) * 100;
}

.my_class {
    .mixin(20, 100);
    width: @result + 0%; // you can use any unit here
}

The above class will have a width of 20%. If we added with px, it would be 20px.

Richard Testani
  • 1,474
  • 4
  • 15
  • 29
1

For some reason the least verbose and most obvious method is sort of missing here (it's in Richard Testani answer actually but there it's hindered with further code leading to a wrong direction). So... The answer to original:

width: ((480/1366)*100)+'%';

is as simple as:

width: (480/1366*100%);

Speaking of percentage:

it does the trick too but personally I'd never use it for its verbosity and non-readability. At quick scanning percentage(480/1366) reads just like peekabooze(480/1366) so you have to stop and stare at it to get a clue. Contrary the explicit appearance of % in 480/1366*100% (or 480 / 1366 * 100%) makes it more easily noticeable.

seven-phases-max
  • 11,765
  • 1
  • 45
  • 57