What is the result of Calc () in CSS

Now we started using calc() in css to set the width as a result of the calculation. For instance:

 <div id='parent'> <div id='calcWidth'></div> </div> #parent{ width:100px; } #calcWidth{ width:calc(100% - 3px); height:100px; background:red; } 

I know how calc() works, but I just want to know what is returned in css, instead of calc(100% - 3px); in the above example.

What is my confusion?

  • In the above example, width:calc(100% - 3px);

  • say that the 100% width is actually 100px to be determined at runtime by css.

  • So, the calculated width will be 100px-3px=97px 97px, and if you convert it to % 97% correctly?

But now there are two possibilities

  • Coming back
  • 97px , which is set as the width.

  • 97% , which is set as the width.

My question is:

In both cases, now the width should be set to 97px , but what returns as a result of width:calc(100% - 3px); , 97px OR 97% ?

you can also see this fiddle: http://jsfiddle.net/8yspnuuw/1/

EDIT: please read

See friends: A simple example:

  <div class='parent'> <div class='child'> </div> </div> .parent{ width:200px; } .child{ width:20% } 

I know that the width of the child will be 160 px when rendering. Good! but is this not what is set in css correctly? css sets it to%, it just displays in pixels.

Similarly, using calc , it returns % or pixel

Or to explain my question, read the answer of BoltClocks , what is the calculated value , (and not the value used, I know what is in pixels)

+5
source share
3 answers

spec does not very accurately determine what the calculated value of the calc() expression is, however, it says that percentages are never calculated as part of the calculated value. How exactly this value is presented remains as a implementation detail.

If you see the length of the pixel instead of the percentage, then this length is the used value, not the calculated value, since the pixel value can be determined only after calculating any percent and laying out the elements.

Note that getComputedStyle() may return results that do not meet the CSS definition of "computed value". This is one of the many unfortunate consequences of the fact that browsers do their job back in the 90s.

+7
source

The widths shown are in pixels. from your example

+5
source

Regardless of the pixel size div calcWidth, a value of 3 decreases from it. For example, if the width of the parent is 200, the width of the calcWidth div will be 197px. therefore it is equal to px, not%

Demo

  document.getElementById('calcWidth').offsetWidth; 

image style in pixel jsdemo

0
source

Source: https://habr.com/ru/post/1214152/


All Articles