如下代码所示,我给div2加上margin-top属性,div1怎么也跟着有了margin-top属性呢?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>absolute + margin auto</title>
<style type="text/css">
div {
width: 100px;
height: 100px;
}
#div1 {
background-color: red;
float: left;
}
#div2 {
margin-top: 30px;
background-color: green;
}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
当我给div1也加上margin-top属性值的时候,div1竟然好像相对于div2进行上外边距的计算:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>absolute + margin auto</title>
<style type="text/css">
div {
width: 100px;
height: 100px;
}
#div1 {
background-color: red;
float: left;
margin-top: 10px;
}
#div2 {
margin-top: 30px;
background-color: green;
}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
根本原因是
div2
和body
发生了上边距的父子折叠,导致两者的顶部是重叠的。div1
会向上浮动到body
的顶部,看起来就是div1
和dvi2
的顶部重叠了。至于给
div1
加了上边距之后,它看起来好像是相对div2
向下移动,还是因为div2
和body
顶部重叠的原因,div1
实际上是相对body
移动的。