意外的< body>被孩子的边缘边缘压低的身体行为 [英] Unexpected <body> body behaviour as it's pushed down by child's margin-top

查看:83
本文介绍了意外的< body>被孩子的边缘边缘压低的身体行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML问题看起来总是如此简单,以至于我几乎不敢问他们.但是,顺便说一句,我不知道为什么会这样.

HTML problems always look so simple that I nearly feel embarassed asking them. But let it be, I have no idea why this is happening.

在此提琴中, http://jsfiddle.net/o5ee1oag/2/主体被推入向下按页眉的边距(50像素):

In this fiddle http://jsfiddle.net/o5ee1oag/2/ body is being pushed down by header's margin(50px):

<body>
 <div id="background"></div>
 <header>
  <ul>
   <li>Button 1</li>
   <li>Button 2</li>
  </ul>
 </header>
</body>

因此div#background {位置:绝对; }也被下推.然后我去萤火虫,应用背景:红色;到身体,整个区域变成红色,包括边距.

In consequence div#background { position: absolute; } is being pushed down too. Then I go to Firebug, apply background: red; to the body and the whole area gets red, with margin included.

1)为什么会发生这种情况,主体距顶部50像素?

1) Why is this happening, the body is 50px from the top?

2)如何防止身体被压下?

2) How do I prevent body from being pushed down?

谢谢:).

推荐答案

display: inline-block;添加到header

JSFiddle- DEMO

JSFiddle - DEMO

header {
    display: inline-block;
    width:100%;
    height:100px;
    margin-top:50px;
    background:rgba(0, 0, 0, 0.4);
}

此问题是由于利润率下降而发生的:

The issue is happening because of the margin collapsing:

您的header元素位于具有最高边距50px的边沿旁边,并且边距组合并应用到该边沿,这会强制该边沿的内容从所应用的折叠边距开始低于(50px),以符合 框模型 .

Your header element is next to the body that have top margin 50px and the margin combine and are applied to the body and this forces the body's content to start below (50px) the applied collapsed margin in compliance with the box model.

div#background具有position: absolute;,并且绝对定位的框可以具有边距,但不会与其他任何边距一起折叠,如果从div#background中删除position: absolute;,则该边距将应用于header,并且不要随身而倒- 演示

The div#background have position: absolute; and the absolutely positioned boxes can have margins but they do not collapse with any other margins, If you remove the position: absolute; from div#background then the margin is applied to header and don't collapsed with the body - DEMO

或::您还可以将top: 0px;添加到div#background- 演示

OR: You could also add top: 0px; to the div#background - DEMO

保证金崩溃规范:

有时将块的顶部和底部边距合并(合拢) 成为一个单一的边距,其大小是合并的边距中最大的一个 它被称为边际崩溃"的行为. -通过 Mozilla MDN

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing. - by Mozilla MDN

阅读更多有关折叠边距行为的信息:

Read More about collapsing margins behavior:

  • W3.ORG - 8.3.1 Collapsing margins
  • Sitepoint - Collapsing Margins

这篇关于意外的&lt; body&gt;被孩子的边缘边缘压低的身体行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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