position: fixed caused element to be wider than browser

前端 未结 6 2597
独厮守ぢ
独厮守ぢ 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:47

    As Salaw mentioned, using body { margin: 0; } will solve the issue, since has default margin/padding (depending on the browser). position: fixed; removes an element completely from the flow of the document and makes it relative only to the viewport, while position: relative; does not.

    Given this fact, and given that width: 90% means "make this element take up 90% of parent element's available space", and given that the parent of a fixed element is the viewport while the parent of this relative element is the body with its margin, you have the discrepancy in sizes.

    See http://codepen.io/anon/pen/exzpC

提交回复
热议问题