Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css calc number division

If I use a calculator, 2/3 is 0.6666666667 which is about 67%. However if I try to do the same thing with css calc I get an error.

width: calc(2 / 3);

Is there a working way for this?

I don't think it looks that good writing it like 0.666666666667. Any ideas are welcome.

like image 825
Jens Törnell Avatar asked Jun 28 '17 14:06

Jens Törnell


People also ask

Can you do Division in CSS?

calc() is a native CSS way to do simple math right in CSS as a replacement for any length value (or pretty much any number value). It has four simple math operators: add (+), subtract (-), multiply (*), and divide (/).

How does Calc () function work on values in CSS?

The calc() function takes a single expression as its parameter, with the expression's result used as the value. The expression can be any simple expression combining the following operators, using standard operator precedence rules: + Addition.

Can you use Calc for padding CSS?

A solution for you would be to use CSS calc, it has good browser support and fixes your issue in quite a simple manner. The only downside here is that it doesn't calculate the padding-top in % but you simply cannot calculate padding-top in % from the height of the element unless you use javascript.


2 Answers

The problem is with calc(2 / 3) you will just get a number without an unit. CSS can't display just a number as width. This would be like if you set width: 3 which obviously doesn't work.

If you want the percentage you will need to muliply it by 100%

width: calc(2 / 3 * 100%);

and if you really want the result in pixels multiply it by 1px

width: calc(2 / 3 * 1px);
like image 169
SvenL Avatar answered Sep 21 '22 23:09

SvenL


Use this:

width: calc(100% / 3 * 2);

As far as I know CSS calc doesn't convert fractions to percentages.

like image 42
Douwe de Haan Avatar answered Sep 17 '22 23:09

Douwe de Haan