文章地址 https://www.cnblogs.com/sandraryan/
案例:用diiv嵌套多个正方形,配合盒模型相关知识,使每个div在他的父元素上居中。(每个div中心点对齐)
涉及到margin的各种合并问题。
(触发BFC是更好的解决方案等,为做练习此处只考虑margin)
此处给div的父级加个border就好了
<!DOCTYPE html> <html lang="en"> <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>Document</title> <style type="text/css"> .first { width: 600px;height: 600px; background-color: red; border: 1px dashed black; } .second { width: 500px;height: 500px; background-color: orange; margin: 50px; /* 使second box在first box上居中显示,first设置了边框所以margin不会合并*/ border: 1px solid orange; } .third { width: 400px;height: 400px; background-color: yellow; /* 此时third和second如果设置margin-top会合并 */ border: 1px solid yellow; margin: 48px; /* 加border就可以使margin-top恢复作用 */ /* 垂直关系视图布局 直接父级元素提供位置的参考 */ } .forth { width: 300px;height: 300px; background-color: green; border: 1px solid green; margin: 48px; } .fifth { width: 200px;height: 200px; background-color: lightblue; border: 1px solid lightblue; margin: 48px; } .center { width: 100px;height: 100px; background-color: purple; margin: 50px; } </style> </head> <body> <div class="first"> <div class="second"> <div class="third"> <div class="forth"> <div class="fifth"> <div class="center"></div> </div> </div> </div> </div> </div> </body> </html>
图片: