为什么固定定位会改变元素的宽度? [英] Why does fixed positioning alter the width of an element?
问题描述
我有一个< div>
,其宽度设置为 100%
。当我添加 position:fixed
时,宽度变为 16px
较大。
I have a <div>
that has its width set as 100%
. When I add position:fixed
to it, the width becomes 16px
larger.
我注意到在身体上,所有边都有 8px
边距,所以我猜猜 position:fixed
在某种程度上忽略了包含它的body标记的边距。
I noticed that on the body, there are 8px
margins on all sides, so I am guessing that position:fixed
is somehow ignoring the margins of the body tag in which it is contained.
我看了一下 MDN参考,但无法找到解释正在发生的事情。
I looked at the MDN Reference but was unable to find anything that explains what is going on.
< div>
是什么导致此行为的 position:fixed
What does position:fixed
changed about the <div>
that causes this behavior?
示例: http://jsfiddle.net / UpeXV /
推荐答案
正文
边距 8px
。因此,当您将元素的 width
设置为 100%
时,它将成为主体的宽度,小于$
The body
automatically has a margin of 8px
. So when you set the width
of your element to 100%
, it becomes the width of the body, less 8px
on both sides.
但是当你给元素 position:fixed
,它不再设置相对于body,而是设置为没有边距的视口。所以 width
现在是视口的宽度,它是2 * 8px
broader -
But when you give the element position:fixed
, it no longer is set relative to the body but to the viewport, which doesn't have margins. So the width
is now the width of the viewport, which is 2 * 8px
wider - the 16px
that you observe.
这里是 W3文档主题:
而position:absolute的元素的位置和尺寸是相对于它的包含块,具有position:fixed的元素的位置和尺寸总是相对于初始包含块。通常是视口:浏览器窗口或纸张页面框。
Whereas the position and dimensions of an element with position:absolute are relative to its containing block, the position and dimensions of an element with position:fixed are always relative to the initial containing block. This is normally the viewport: the browser window or the paper’s page box.
这篇关于为什么固定定位会改变元素的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!