Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate percentages in LESS CSS?

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.

like image 411
HappyElephant Avatar asked Jan 06 '12 17:01

HappyElephant


People also ask

How are CSS percentages calculated?

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as none .


2 Answers

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);
like image 199
zzzzBov Avatar answered Oct 04 '22 01:10

zzzzBov


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);
}
like image 44
anddoutoi Avatar answered Oct 04 '22 01:10

anddoutoi