位置:修复了导致元素比浏览器宽的问题 [英] position: fixed caused element to be wider than browser

查看:38
本文介绍了位置:修复了导致元素比浏览器宽的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么position:fixed导致元素比页面上的浏览器或其他内容宽并且导致水平滚动?

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?

这是代码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;
}

这里是指向Codepen的链接 http://codepen.io/colbydodson/pen/wcgua

Here is a link to the codepen http://codepen.io/colbydodson/pen/wcgua

推荐答案

这是因为宽度根据容器的不同而分别应用于 relative fixed 元素可以继承父项的margin 和style属性-分别对应于它们的 position 属性,例如(您猜对了) width .

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.

由于,如果您不使用任何CSS重置,例如丑陋的家伙 * {margin:0;padding:0;}
body 标签将具有默认的8px边距( http://www.w3.org/TR/CSS2/sample.html ),

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 固定没有任何顶部左侧 right bottom 值将定位到最近的可用位置->,但将继承原始文档/视口的大小,使其真正宽90%,刚刚定位在10px主体"边距偏移处.

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.

要测试,请添加 top:0;left:0; (对于固定的 标题)

To test add top:0; left:0; for the fixed header http://jsbin.com/ETAqADu/1/edit

.container 是设置为 relative 位置的 block 级别DIV元素,将是可用父级可用宽度的90%宽度,即是 body innerWidth(不计算10 + 10px的边距(X轴))

.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))

结果:从逻辑上讲, header .container 宽20px,因为位置固定可将元素移出 body 流.

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

修复:从逻辑上讲,通过设置为0,控制您的父( body )元素的默认边距

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

这篇关于位置:修复了导致元素比浏览器宽的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆