[英]100% width on position absolute element
I'm trying to make a div
to have 100% width of its parent element ( body
). 我正在尝试使
div
具有100%宽度的父元素( body
)。 body
has a horizontal scrollbar and the div
only takes up the viewport width. body
有一个水平滚动条, div
只占用视口宽度。 To fix this I added 为了解决这个问题我添加了
width: inherit;
to it. 它。 I expected it to work since
inherit
, according to the definition , means "taking the computed value of the property from its parent element". 我希望它能够工作,因为
inherit
,根据定义 ,意味着“从其父元素中获取属性的计算值”。 I tested it in a simpler model and it works: http://jsfiddle.net/DerekL/EYgT9/ . 我在一个更简单的模型中测试它并且它可以工作: http : //jsfiddle.net/DerekL/EYgT9/ 。
However, when I apply the code to my actual project it doesn't work as expect. 但是,当我将代码应用于我的实际项目时,它无法按预期工作。 It doesn't even seem to follow the definition.
它似乎甚至没有遵循这个定义。
As you can see, the div
has inherit
as its width
. 如您所见,
div
inherit
了它的width
。 But it's computed width is not the width of its parent body
, instead it's some other value 302px
. 但它的计算宽度不是其父
body
的宽度,而是其他值为302px
。
Now let's take a look body
: 现在让我们来看看
body
:
body
clearly has a width of 470px
. body
明显宽度为470px
。
I couldn't figure out what's the reason behind this, making it not working as expected. 我无法弄清楚这背后的原因是什么,使它无法按预期工作。 The overall structure is the same as the fiddle, but result aren't the same.
整体结构与小提琴相同,但结果不尽相同。
What are the possible reason of this happening? 发生这种情况的可能原因是什么? Sorry that I couldn't post the relevant part of the code since I don't even where it's causing this issue.
很抱歉,我无法发布代码的相关部分,因为我甚至没有发布导致此问题的地方。
This is because the element with position:absolute
is positioned in reference to <html>
since <body>
doesn't have a position to put it in reference to. 这是因为具有
position:absolute
的元素position:absolute
<html>
引用中,因为<body>
没有位置可以引用它。 Thus, it's inheriting its width from html
as well. 因此,它也从
html
继承了它的宽度。
To fix it, add position:relative
to body
要修复它,添加
position:relative
对于body
Your body tag has position static and for the position absolute to work properly the parent element must have position set on either relative or absolute. 你的body标签的位置是静态的,对于绝对的位置,父元素必须在relative或absolute上设置位置。 Just add position: relative or absolute;
只需添加位置:相对或绝对; to the body tag.
到身体标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.