为什么顶部div的margin-top适用于`< body>`? [英] Why margin-top of the top div would apply to `<body>`?

查看:139
本文介绍了为什么顶部div的margin-top适用于`< body>`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我发布了一个演示 http://jsfiddle.net/LxYMv/1/

Here I posted a demo http://jsfiddle.net/LxYMv/1/.

正如你可以看到< body> 得到margin-top:从顶部div 10px,因此 ; html> 的黑色背景泄漏出来。这是否意味着我不能给顶部div一个正的margin-top?

As you can see <body> gets margin-top:10px from the top div, and therefor <html>'s black background leaks out. Does it mean that I can't give the top div a positive margin-top?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <style>
            html{color:#000;background:#FFF}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,select,p,blockquote,th,td{margin:0;padding:0}table{border-collapse:collapse;border-spacing:0}fieldset,img{border:0}address,button,caption,cite,code,dfn,em,input,optgroup,option,select,strong,textarea,th,var{font:inherit}del,ins{text-decoration:none}li{list-style:none}caption,th{text-align:left}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal}q:before,q:after{content:''}abbr,acronym{border:0;font-variant:normal}sup{vertical-align:baseline}sub{vertical-align:baseline}legend{color:#000}
            html{background:black}
            body{background:white}
        </style>
    </head>
    <body>
        <div style="margin-top:10px;background:red;height:100px">Here the top div begins</div>
        <div style="height:800px">A long long div</div>
    </body>
</html>


推荐答案

这称为汇总折叠

当带有边距的元素在没有填充或边框的元素内时,边距将应用于父元素之外,而不是子元素和父边界之间。

When an element with a margin is inside an element with no padding or border, the margin will be applied outside the parent element instead of between the child element and the parent edge.

这种行为的基本原因是margin指定了最小的区别元素之间,而不是像padding这样的元素周围的距离指定了元素内容周围的距离。

The basic reason for this behaviour is that margin specifies the minimum distinace between elements, not a distance around an element like padding specifies distance around the element content.

这篇关于为什么顶部div的margin-top适用于`&lt; body&gt;`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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