Why does fixed positioning alter the width of an element?

本秂侑毒 提交于 2019-12-30 08:10:04

问题


I have a <div> that has its width set as 100%. When I add position:fixed to it, the width becomes 16px larger.

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.

I looked at the MDN Reference but was unable to find anything that explains what is going on.

What has position:fixed changed about the <div> that causes this behavior?

Example: http://jsfiddle.net/UpeXV/


回答1:


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.

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.

Here's the W3 documentation on the subject:

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.




回答2:


This is the default behavior for fixed elements, since a fixed element does not orientate itself in context to its closest positioned parent but the viewport, thus getting fixed in the window. The 16px more width come from the fact, as you pointed out yourself, that the body has a default margin of 8px.




回答3:


If you need the fixed element to be 100% width, and you still want space, you can consider using box-sizing: border-box. Then use padding, rather than margins, to create space. This will allow the fixed element to span the width of the page without going over. Margins and borders and padding are always added to the dimensions of an element, unless you use the border-box model, in which case width will include padding and borders.

See: http://css-tricks.com/box-sizing/




回答4:


It looks like when you set an element to position:fixed, it takes on the width of the viewport instead of its parent.

Fixed positioning is similar to absolute positioning, with the exception that the element's containing block is the viewport.

MDN CSS Position Reference

Thanks for your comments.



来源:https://stackoverflow.com/questions/16442457/why-does-fixed-positioning-alter-the-width-of-an-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!