8

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.

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

5 Answers5

21

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);
SvenL
  • 1,904
  • 8
  • 10
  • Great answer! Then to add a unit, we need to multiply it with 1 and the unit suffix. Because 100% is the same as 1 we multiply with 100 instead of 1. – Jens Törnell Jun 28 '17 at 17:04
3

Use this:

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

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

Douwe de Haan
  • 6,247
  • 1
  • 30
  • 45
2

Just for completeness, I think this should work as well, just for this case:

width: calc(200% / 3);

Yet untested.

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
1

You need to multiply by 100 to convert it into %

div{
  background-color: red;
  width: calc( (2/3)*100% );
  
}
<div>yeah</div>
Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32
1

In your example, you have no units defined, and the width of a certain element cannot be unitless. You would need to convert the width into pixels, percentages or similar unit.

For example:

width: calc(100px / 2) // the result will be pixels
width: calc(100% / 2) // the result will be in percentages
width: calc(100 / 2 * 1px) // the result will be in pixels

There is a great article explaining the calc() function here.

Nesha Zoric
  • 6,218
  • 42
  • 34