Search code examples
csscss-calc

What Is Result Of calc() In CSS


We have now started using calc() in css, for setting widths on a result of calculation. For example:

<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, in the place of calc(100% - 3px); in the example given above.

Whats my confusion?

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

  • say the 100% width is actually 100px, which will be determined at runtime by css.

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

But now, there are two possibilities

  • 97px is returned, which is set as a width.

  • 97% is returned, which is set as a width.

My Question is:

In both cases now the width shall be set to 97px, but what is returned 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: Take a simple example:

 <div class='parent'>
    <div class='child'>
    </div>
    </div>

.parent{
width:200px;
}
 .child{
  width:20%
  }

I know the width of child will become 160 px when it is rendered. okay! but thats not what is set in css right? css sets it in %, it is just rendered in pixels.

So similarly, using calc, does it return % or pixel

Or to explain my question, read BoltClocks answer, what is the computed value, (and not the used value, i know that is in pixels)


Solution

  • The spec does not define very strictly what the computed value of a calc() expression is, however it does say that percentages are never calculated as part of the computed value. How exactly this value is represented is left as an implementation detail.

    If you see a pixel length instead of a percentage, then that length is the used value, not the computed value, because the pixel value can only be determined after calculating any percentages and laying out elements.

    Note that getComputedStyle() may return results that are inconsistent with the CSS definition of "computed value". This is one of many unfortunate consequences of browsers doing their own thing back in the 90s.