Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

percentage value in css calc

Tags:

While specifying a percentage value in css calc, how does calc know whether I am referring to width or height?

.container {
    width: calc(100% - 2vw); // 100% here is width or height ?
}

One may assume that it is either width or height depending on the property you are accessing, (width in this case). If that were the case, what happens if you would like to do some calculation based on a different property? For instance, set the width based on some calculation of height? Say, set the container width to be 1.5 times height?

like image 445
binish Avatar asked Apr 12 '19 19:04

binish


2 Answers

From the specification

The computed value of a calc() expression is the expression with all components computed.

Where percentages are not resolved at computed-value time, they are not resolved in calc() expressions, e.g. calc(100% - 100% + 1em) resolves to calc(1em + 0%), not to 1em. If there are special rules for computing percentages in a value (e.g. the height property), they apply whenever a calc() expression contains percentages.

There is no magic when using percentage inside calc() they will simply behave as if you aren't using calc().

So using width:100% is exactly the same as width:calc(100%) which is also the same as calc(50% + 50%). when you add another unit like width:calc(100% - 2em) it's like calculating width:100% then you remove 2em from it.

Basically, calc() is useful when combining percentage and non-percentage value in order to have accurate and precise result like removing 10px from 50% of the total width by using width:calc(50% - 10px).


what happens if you would like to do some calculation based on a different property? For instance, set the width based on some calculation of height?

You cannot do such thing with calc(). CSS in general doesn't allow such thing. You can either consider JS, some hacks to preserve ratio between width/height or use CSS variable and assign the same value for different properties.


Related question where the use of calc() combined with CSS variable is missused: Calc() outputting unexpected value

like image 101
Temani Afif Avatar answered Sep 17 '22 11:09

Temani Afif


To answer the second part of the question:

For instance, set the width based on some calculation of height? Say, set the container width to be 1.5 times height?

You can do this with the aspect-ratio property:

.container {
  text-align: center;
  height: 200px;
  /* width / height ratio */
  aspect-ratio: 1 / 1.5;
  background: lightgray;
}
<div class="container">
  some content
</div>
like image 20
Jacob Avatar answered Sep 16 '22 11:09

Jacob