cssposition

Why does fixed positioning alter the width of an element?


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/


Solution

  • 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.