position: fixed caused element to be wider than browser

前端 未结 6 2612
独厮守ぢ
独厮守ぢ 2021-02-20 13:04

Can anyone tell me why position:fixed cause the element to be wider than the browser or other content on the page and causing horizontal scrolling?

Here is the code HTML

6条回答
  •  [愿得一人]
    2021-02-20 13:56

    It's because the width is differently applied to relative and fixed elements depending on the container margin and the style property that are parent-inheritable - respective to their position property such as (you guess right) width.

    Due to, if you don't use any CSS reset like this ugly fella *{margin:0; padding:0;}
    the body tag will have it's default 8px margins (http://www.w3.org/TR/CSS2/sample.html),

    header 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 REALLY 90% wide, just 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 + 10px margins (X axis))

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

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

提交回复
热议问题