我在这里发布了一个演示 http://jsfiddle.net/LxYMv/1/ .
如你所见<body>
从顶部 div 获取 margin-top:10px,因此 <html>
的黑色背景泄漏。这是否意味着我不能给 top div 一个正的 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>
最佳答案
这叫做 margin collapsing .
当带有边距的元素位于没有填充或边框的元素内部时,边距将应用于父元素外部,而不是应用于子元素和父边缘之间。
此行为的基本原因是边距指定元素之间的最小距离,而不是元素周围的距离,如填充指定元素内容周围的距离。
关于html - 为什么顶部 div 的 margin-top 将适用于 `<body>` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7579000/