CSS 中 calc() 的结果是什么

What Is Result Of calc() In CSS

我们现在开始使用 css 中的 calc() 来设置计算结果的宽度。 例如:

<div id='parent'>
<div id='calcWidth'></div>
</div>


   #parent{
           width:100px;
           }
   #calcWidth{
            width:calc(100% - 3px);
            height:100px;
            background:red;
           }

我知道 calc() 是如何工作的,但我只想知道 return 在 css 中编辑了什么,代替上面给出的示例中的 calc(100% - 3px); .

我的困惑是什么?

但是现在,有两种可能

我的问题是:

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% ?

你还可以看到这个fiddle: http://jsfiddle.net/8yspnuuw/1/

编辑:请阅读

看朋友:举个简单的例子:

 <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.

所以类似地,使用 calc, 是 return % 还是 pixel

或者为了解释我的问题,请阅读 计算值是什么,(而不是使用值,我知道它以像素为单位)

呈现的宽度以像素为单位。

无论 calcWidth div 的像素大小是多少,值 3 都会从中减少。例如,如果父级的宽度为 200,则 calcWidth div 的宽度将为 197px .所以它是 px 而不是 %

Demo

 document.getElementById('calcWidth').offsetWidth;

spec 没有非常严格地定义 calc() 表达式的计算值是什么,但是它确实表示百分比永远不会作为计算值的一部分进行计算。这个值是如何表示留作实现细节。

如果您看到的是像素长度而不是百分比,则该长度是使用值,而不是计算值,因为像素值只能在计算任意值后确定百分比和布局元素。

请注意,getComputedStyle() 可能 return 结果与 "computed value" 的 CSS 定义不一致。这是浏览器在 90 年代自行其是的众多不幸后果之一。

CSS 不支持动态值(包括像 width: 100%; 这样的简单百分比值)。这意味着 calc() 中的 100% 最初被转换为 px 一次,而不是连续转换。

这已经回答了你的问题。 % 值被转换为 px,最终得到 97px。您可以通过 window.getComputedStyle() 或截屏并测量来确认。

calc() 没有计算值;它发生在渲染时——这就是为什么你可以混合单位。