33

I would like to calculate the width of child-container (div etc) in percentages depending on the parent container with LESS CSS.

I am using the forumula by Ethan Marcotte: target / context = result.

Parent container: 620px
Child container: 140px

I am using this calculation:

div.child-container {
    width: (140/620)*100%;
}

However the output is:

div.child-container {
    width: 0.2258064516129;
}

I would like to move the decimal point two digits and add the %, like this:

div.child-container {
    width: 22.58064516129%;
}

Any hints greatly appreciated.

HappyElephant
  • 333
  • 1
  • 3
  • 6
  • `100% == 1`, so the math makes sense. – zzzzBov Jan 06 '12 at 18:00
  • 2
    The output is looking right for me given your input. – scottheckel Jan 06 '12 at 18:01
  • @zzzzBov Thanks, I tried using *10000% in order to move the decial point and it works, but somehow the % sign is removed each time. The bottom sample is what I need as parsed output though. – HappyElephant Jan 06 '12 at 18:04
  • 2
    My experience with LESS CSS is just looking up information related to this question, so I'm going to go out on a limb and say you need it to say `width: 100%*(140/620);` because I read that it picks the units off of the first value in the equation. – zzzzBov Jan 06 '12 at 18:09
  • @Hexxagonal is right - the output is correct, you are probably using an old or nonstandard version of the LESS parser. How are you parsing your LESS? Less.JS newer versions should do it right. – Nathan Strutz Jan 06 '12 at 21:53

3 Answers3

51

According to the LESS CSS website, you need to change the order of your equation

The output is pretty much what you expect—LESS understands the difference between colors and units. If a unit is used in an operation, like in:

@var: 1px + 5;

LESS will use that unit for the final output—6px in this case.

It should be:

width: 100%*(140/620);
illright
  • 3,991
  • 2
  • 29
  • 54
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
27

Maybe the percentage function didn't exist when OP was asking but for future reference I add this answer.

div.child-container {
    width: percentage(140/620);
}
anddoutoi
  • 9,973
  • 4
  • 29
  • 28
  • Just for information. I tried `percentage((@index / 10) - 0.01);` and it didn't work I had to add more parenthesis `percentage(((@index / 10) - 0.01));` I'm telling because maybe someone wants to do more "difficult" maths as I did, not just a division. – Shil Nevado Sep 22 '16 at 16:05
  • I think this is a lot cleaner than the OP's selected answer. Both work, but this is a lot more straight forward. – drewkiimon Dec 06 '18 at 22:23
0

As for 2022, LESS 4.0 and division operator concerned:

From 4.0, No division is performed outside of parens using / operator.

@color: #222 / 2; // results in `#222 / 2`, not #111 (!)
background-color: (#FFFFFF / 16); //results is #101010

See the docs.

Valentine Shi
  • 6,604
  • 4
  • 46
  • 46