CSS 反向宽度的 calc() 不工作

CSS calc() for inverse width isn't working

我有一个元素,我想在 width 中增加,因为它的父元素在 width

中减少

等式应如下所示:

width:calc(150 + 500 / 100%);

但至少在 Chrome 中它说每当我尝试除以百分比宽度时 属性 是无效的。

这可能吗? (可以接受 calc() 的替代方案)

编辑 我添加了空格(没有意识到这一点)。尝试了各种单位,还没有运气。

Fiddle

<div style="width:100%;position:relative;">
    <div style="width:calc(150px + (500 / 100%));position:absolute;top:0;left:0;">This one should get bigger as the page gets smaller</div>
</div>

思考过程:

固定宽度 (150px) 加上 500 除以当前父宽度。

所以如果父级是 500px:

150 + 500/500 -> 150 + 1 = 151

父级为 100px

150 + 500/100 -> 150 + 5 = 155

父级为 20px

150 + 500/20 -> 150 + 100 = 250

calc() 运算符之间需要空格(但仅在 +- 中),但您缺少单位,可能是 pxem,rem 等等...,这样的事情也是如此:

width:calc(150px + (500px / 100%)) 

这是无效的,因为正如@TylerH 所解释的那样,您不能除以未编辑的值(px% 等)。

但如果可能的话,当你除以 100% 时你会乘以 1,所以基本上你会保持不变,因为 1 是乘法的中性值,所以这样做是没有用的。


很难知道,因为你的问题没什么可看的,而且仍然无效,但我猜你正在寻找这样的东西:

width:calc(150px + (100% / 500px)) 

鉴于你编辑过的问题 AFAIK 你必须使用 JS 来实现这个,除非你可以提供 Fiddle.

解决方法简单得令人难以置信。将 500px 移动到第一部分并减去宽度。

width:calc(650px - 100%);

随着其父级变窄而变宽。

Updated fiddle

看来您已经找到了解决方案,但我会具体回答为什么您的原始代码不起作用:

我将从 calc() 中乘积方程式(除法时)的语法开始:

<calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]

spec for the calc() property syntax is a bit more complicated than it sounds. When dividing in calc() as you're doing here, the right side must be a number。您不能使用“单位化”值:

Number values are denoted by <number>, and represent real numbers, possibly with a fractional component.

When written literally, a number is either an integer, or zero or more decimal digits followed by a dot (.) followed by one or more decimal digits and optionally an exponent composed of "e" or "E" and an integer. It corresponds to the production in the CSS Syntax Module. As with integers, the first character of a number may be immediately preceded by - or + to indicate the number’s sign.

也就是说,您不能将某物 除以 百分比值,如 100%。