html - 位置 : fixed caused element to be wider than browser

标签 html css

谁能告诉我为什么 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;
}

这是代码笔的链接 http://codepen.io/colbydodson/pen/wcgua

最佳答案

Width 以不同方式应用于 relativefixed 元素,祖先 margin 和样式属性是就其 position 属性而言,父级可继承。

body 标签将具有默认的用户代理样式表 8 像素边距 ( http://www.w3.org/TR/CSS2/sample.html ),

header 90% 宽度,固定没有任何topleftrightbottom 值将定位到最近的可用位置,但将继承原始 文档/视口(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; }

另请阅读 CSS Box Model - Margin collapsing

关于html - 位置 : fixed caused element to be wider than browser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556014/

相关文章:

html - float 元素行为

css - 为什么这个页面在IE7和IE8中显示不一样

html - 火狐 : no CSS errors/warnings in the log

javascript - Bootstrap 下拉列表

internet-explorer - Internet Explorer 渐变显示为蓝色

internet-explorer - IE10 破坏了在 Webkit 和 Firefox 中工作的 CSS3 3D 动画

javascript - 如何使用 Canvas 创建动画形状的无限循环?

javascript - CSS 在 192 行后不起作用

html - 如何在 Chrome 中显示完整的数据列表下拉列表?

css - 带文本背景的标题