谁能告诉我为什么 position:fixed 导致元素比浏览器或页面上的其他内容宽并导致水平滚动?
代码如下 HTML
<header>
this is a header
</header>
<div class="container">
this is a container
</div>
CSS
header {
width: 90%;
height: 100px;
background: blue;
position: fixed;
z-index: 100;
}
.container {
width: 90%;
height: 500px;
background: red;
position: relative;
z-index: -2;
}
最佳答案
Width 以不同方式应用于 relative
和 fixed
元素,祖先 margin
和样式属性是就其 position
属性而言,父级可继承。
body
标签将具有默认的用户代理样式表 8 像素边距 ( http://www.w3.org/TR/CSS2/sample.html ),
header
90% 宽度,固定,没有任何top
,left
、right
或 bottom
值将定位到最近的可用位置,但将继承原始 文档/视口(viewport)大小,使其成为现实90% 宽,但位于 10px 的“正文”边距偏移处。
要测试添加 top:0; left:0;
为 fixed header
http://jsbin.com/ETAqADu/1/edit
.container
是 block 级 DIV 元素,设置为 relative
位置,宽度为可用父级可用宽度的 90%,即 body
innerWidth(不计算 X 轴上的 10 + 10 px 边距)
不需要的结果:
逻辑上 header
将比 .container
宽 20 像素,因为位置固定会将您的元素移出 body
流。
修复:
通过设置为 0
body
)元素的默认边距
body { margin: 0; }
或者一个小而重的 CSS 重置,比如:
/* QuickReset */
*, *::before, *::after { margin: 0; box-sizing: border-box; }
关于html - 位置 : fixed caused element to be wider than browser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556014/