gpt4 book ai didi

html - 位置 :fixed and width:inherit with percentage parent

转载 作者:太空狗 更新时间:2023-10-29 13:14:54 25 4
gpt4 key购买 nike

我正在尝试为 fixed 元素指定父级百分比的 width(此处为 #container)。当我使用像素而不是百分比时,它就起作用了。我该怎么做?这可以通过 CSS 实现吗?

HTML

<div id="outer">
<div id="container">
<div id="fixed">
Sitename
</div>
</div>
</div>

CSS

#outer{
width:300px;
border: 1px solid yellow;
}

#container {
width: 90%; /*When I use e.g 250 px it works. But I need it in percentage*/
border: 1px solid red;
height: 300px;
}

#fixed {
position: fixed;
width: inherit;
border: 1px solid green;
}

JSFiddle

添加:

我需要position:fixed。因为我想像这样把它放在页面底部:

JSFiddle

position:relativ 的解决方案对我不起作用。

最佳答案

有一种观点认为,继承值是从相对值(如百分比)“转换”为绝对值。你猜怎么着?这是错的。以下是 MDN 对它的描述:

The inherit CSS-value causes the element for which it is specified to take the computed value of the property from its parent element.

[...]

The computation needed to reach the computed value for the property typically involves converting relative values (such as those in em units or percentages) to absolute values. For example, if an element has specified values font-size: 16px and padding-top: 2em, then the computed value of padding-top is 32px (double the font size).

However, for some properties (those where percentages are relative to something that may require layout to determine, such as width, margin-right, text-indent, and top), percentage specified values turn into percentage computed values. [...] These relative values that remain in the computed value become absolute when the used value is determined.


现在举个例子。假设我们有以下结构:

<div id="alpha">
<div id="bravo">
<div id="charlie"></div>
</div>
</div>

...和以下 CSS:

#alpha { outline: 1px solid red; width: 420px; height: 100px; }
#bravo { outline: 1px solid green; width: 50%; height: inherit; margin: 0 auto; }
#charlie { outline: 1px solid navy; width: inherit; height: inherit; margin: 0 auto; }

...你会看到这张图片:

Width Inheritance Illustration

... 意味着虽然 #charlie 元素与其 #bravo 父元素具有相同的高度,但其宽度是其父元素的 50%。继承的是一个计算值:100px 高度,50% 宽度。


虽然这个特性可能是好是坏,视情况而定,对于非固定元素,它似乎肯定会伤害固定元素。由于 width 属性的 50% 值按原样继承,因此该维度的 used value 将基于视口(viewport)。这与 percentage-using 值相同,例如 calc(50%)

关于html - 位置 :fixed and width:inherit with percentage parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17011195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com