css乱象:fixed元素被margin牵着鼻子走?

2018-08-25  本文已影响0人  BiiHug

本以为position:fixed元素脱离了文档流完全不会被底部文档流影响,但在做网页练手的时候发现完全不是这样。举个例子,网页底部有一个#test1 的空元素,设置它的margin-top: 30px。在网页顶部设置一个默认position:fixed元素。具体代码如下:

<style type='text/css'>
  #test2 {
    margin-top: 30px;
  }
  #test1 {
    position: fixed;
    width: 500px;
    height: 300px;
    background-color: blue;
  }
  </style>
  </head>
  <body>
    <div id="test2">
    </div>
    <div id="test1">
    </div>
  </body>

最后效果显示为:


1_1.png

显然,位于网页顶部的#test2受到了#test1margin-top的影响。
可以很明显地发现问题的最大原因是在于没有对position:fixed元素的offset properties(偏移特性):top, bottom, left and right进行设置。
但为什么最后显示效果会是这样呢?在SO上找到了详细的解答

所以我们会得到如上图所示的效果。

上一篇 下一篇

猜你喜欢

热点阅读