margin重叠现象

时间:2023-03-09 19:13:11
margin重叠现象

1.上下/左右相邻的普通元素margin,不是两者相加之和,而是取最大值,这个现象叫做margin重叠。 
2. 普通元素才会发生margin重叠,如果是float元素,就不会发生。margin是两者相加之和。

例如:1普通元素

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>练习(margin重叠现象)</title>
<style>
#test1{
height: 100px;
background: blue;
margin-bottom: 50px;
}
#test2{
height: 100px;
background: green;
margin-top:50px;
}
</style>
</head>
<body>
<div id="test1"></div> <div id="test2"></div>
</body>
</html>

margin重叠现象

2,浮动元素:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>练习(margin重叠现象)</title>
<style>
#test1{
height: 100px;
width: 200px;
background: blue;
margin-bottom: 50px;
float: left;
}
#test2{
height: 100px;
width: 200px;
background: green;
float: left;
clear: left;
margin-top:50px;
}
</style>
</head>
<body>
<div id="test1"></div>
<div id="test2"></div> </body>
</html>

margin重叠现象

3,父子(普通元素)发生margin重叠现象

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>练习(margin重叠现象)</title>
<style>
#test1{
height: 150px;
width: 200px;
background: blue; }
#test2{
height: 50px;
width: 50px;
background: green; margin-bottom:50px;
}
#test3{
height: 50px;
width: 50px;
background: green;
margin-top: 50px;
}
</style>
</head>
<body>
<div id="test1">
<div id="test2"></div>
<div id="test3"></div>
</div>
</body>
</html>

margin重叠现象

4,父子(子为浮动元素)不发生margin重叠

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>练习(margin重叠现象)</title>
<style>
#test1{
height: 150px;
width: 200px;
background: blue; }
#test2{
height: 50px;
width: 50px;
background: green;
float: left;
margin-bottom:50px;
}
#test3{
height: 50px;
width: 50px;
background: green;
float: left;
clear: left;
margin-top: 50px;
}
</style>
</head>
<body>
<div id="test1">
<div id="test2"></div>
<div id="test3"></div>
</div>
</body>
</html>

margin重叠现象