html部分:
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Margin重叠</title> <link rel="stylesheet" href="style.css"> </head> <body> <!-- 嵌套关系 div2的margin将是基于外层,而不是基于div1,溢出 --> <!-- 处理:父级封顶;在父类中添加文字、加边框、overflow:hidden、padding --> <div class="div1"> 我是对div2封顶... <div class="div2"></div> </div> <!-- 平级的元素margin取最大值 --> <!-- 处理:浮动、inline-block --> <div class="div3"></div> <div class="div4"></div> </body> </html>
css部分:
div { width: 100px; height: 100px; } .div1 { background-color: aliceblue; /* border: 1px solid gray; */ /* overflow: hidden; */ /* padding: 1px; */ } .div2 { background-color: aquamarine; margin: 60px; } .div3 { background-color: antiquewhite; margin: 10px; /* float: left; */ } .div4 { background-color: aqua; margin: 30px; /* float: left; */ /* display:inline-block; */ }