position: fixed caused element to be wider than browser

I was having a similar problem only on mobile. Despite having no margins, borders, padding on any of the parents, my fixed element was still wider than the viewport, and I didn't have the option of using width: auto.

If you're willing to not support IE8 and below, you can use

width: 100vw

Can I use Viewport units: vw, vh, vmin, vmax


Width is differently applied to relative and fixed elements, the ancestors margin and the style property that are parent-inheritable in respect to their position property.

The body tag will have it's default User Agent Style Sheet 8px margins (http://www.w3.org/TR/CSS2/sample.html),

header 90% width, being fixed, without any top, left, right or bottom value will be positioned to the nearest available place, but will inherit the original document/viewport size, making it in reality 90% wide, but positioned at the 10px 'body' margin offset. To test add top:0; left:0; for the fixed header http://jsbin.com/ETAqADu/1/edit


.container being a block-level DIV element set to relative position, will be 90% width of the available parent usable width, which is the body innerWidth (not counting the 10 + 10 px margins on the X axis)

Unwanted result:
logically header will be 20px wider than .container because position fixed moves your element out of body flow.

Fix:
control your parent (body) element default margin by setting to 0

body { margin: 0; }

Or a small but heavy CSS reset like:

/* QuickReset */
*, *::before, *::after { margin: 0; box-sizing: border-box; }

Read also CSS Box Model - Margin collapsing

Tags:

Html

Css