为什么这个nav会掉下来呢?

我给#main加的margin-top啊 为什么#nav会掉下来?
图片描述

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
    *{margin:0 ;padding:0}
    html, body {
        position: relative;
        height: 100%;
    }
    html{-webkit-text-size-adjust:none;}
    #nav{width: 100%;height: 50px;background-color: blue;position: fixed;z-index: 999999999;}
    #main{min-height: 100%;width: 100%;margin-top: 50px}
    </style>
</head>
<body>
<div id="nav">
</div>
<div id="main">
</div>
</body>
</html>
阅读 3.8k
5 个回答

nav 作为 fixed 是根据其父元素链上第一个非 static position 的元素来定位的,
在这里会找到 body。
然后你可以看到 body 并不是沿着屏幕上边缘定位的,这是因为 body 的内容是从 #main 的内容开始的,于是当 body 的子元素 #main 有一个 margin-top 的时候,body 会拥有一个和他的子元素一样的 margin-top。
所以平时应该尽量不要给 body 的第一个子元素设置 margin-top,而是改成为 body 设置 padding-top。

如果帮到你请投 up 或者接受答案

一直在关注这个问题,其实BFC和Margin Collapse才是正确的方向,所采纳的答案只不过是表象-算作经验而非知识,很难推而广之。
关于BFC推荐一篇好文: 理解BFC - Block formatting context
关于Margin Collapse先看一个定义

Css2.1规范:In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.
中文润色一下是:所有毗邻的两个或更多盒元素的margin将会合并为一个margin共享之(合并时取其大的,不是相加)。毗邻的定义为:同级或者嵌套的盒元素(即子元素和父元素之间也可能发生这个现象),并且它们之间没有非空内容、 Padding或Border分隔。

这就是所谓的Margin Collapse, body作为普通box容器,与其下紧邻的非BFC box #main 发生margin collapse, #nav作为fixed box,默认top是auto,其值以fixed元素出现在html中的位置为准,而body因为共享了#main的margin,相当于body上沿有个padding-top, 导致 #nav默认下移。

解决方案(或的关系)

  1. 给body加 overflow:hidden, 触发它的BFC (从本例中body的height 100%也可以看出,设置一个overflow是恰当的)
  2. 给body加 padding 或 border, 打破发生 margin collapse的条件
  3. 显式的给 #nav更新 top属性
  4. 给#main设置 postion:absolue, 或display:inline-block 触发它的BFC
  5. 即使给#main和#nav再包一层,也要这层有设置 boder或者 padding 或者 overflow-hidden

BFC(Block formatting context)了解一下,面试必考

你的body与#main的margin重叠了,你可以让body生成BFC,使两者边距不重叠

满足以下条件之一即可创建BFC(不全)

  • 根元素或其它包含它的元素
  • 浮动元素 (元素的 float 不是 none)
  • 绝对定位元素 (元素具有 position 为 absolute 或 fixed)
  • 内联块 (元素具有 display: inline-block)
  • 表格单元格 (元素具有 display: table-cell,HTML表格单元格默认属性)
  • 表格标题 (元素具有 display: table-caption, HTML表格标题默认属性)
  • 具有overflow 且值不是 visible 的块元素,
  • display: flow-root
  • column-span: all 应当总是会创建一个新的格式化上下文,即便具有 column-span: all 的元素并不被包裹在一个多列容器中
新手上路,请多包涵

给#nav加top: 0;

给#nav position="fixed" 加位置固定 top:0;left:0;

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题