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 actually100px
, 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 ofwidth:calc(100% - 3px);
,97px
OR97%
?
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)
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.
The rendered widths are in pixels.

Whatever the pixels size of the calcWidth div is, the value 3 is reduced from it..for example if the width of parent is 200 the calcWidth div's width will be 197px. so it is px and not %
document.getElementById('calcWidth').offsetWidth;

CSS does not support dynamic values (bedides simple percentage values like width: 100%;
). That means the 100%
within calc()
are converted one time initially to px
and not continiously.
That already answers your question. The %
-value gets converted into px
end you end up with 97px
. You can confirm that with window.getComputedStyle()
or by taking a screenshot and measure it.
来源:https://stackoverflow.com/questions/28715872/what-is-result-of-calc-in-css