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/
An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element. A fixed element does not leave a gap in the page where it would normally have been located.
To convert it to a fixed-width layout, simply add a fixed with to the #wrapper and set the margins to auto. Setting the margins to auto will cause the left and right margins to be equal no matter how wide the browser window is, which will cause your fixed-width layout to be positioned in the center of the browser.
Fixed positioning is really just a specialized form of absolute positioning; elements with fixed positioning are fixed relative to the viewport/browser window rather than the containing element; even if the page is scrolled, they stay in exactly the same position inside the browser window.
Fixed positioning allows you to fix the position of an element to a particular spot on the page, regardless of scrolling. Specified coordinates will be relative to the browser window. You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With