What Is Result Of calc() In CSS

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

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)

回答1:

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.



回答2:

The rendered widths are in pixels.



回答3:

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 %

Demo

 document.getElementById('calcWidth').offsetWidth; 



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!