小编今天总结了:九种关于盒子居中的方法,并且兼容性非常好,代码如下:
页面骨架如下:
1 2 3 4 5 6 7 8 9 10 11 12
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="parent"> <div class="child"></div> </div> </body> </html>
|
第一种居中方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| .parent{ width: 400px; height: 200px; background: red; padding:50px 100px; box-sizing: border-box; //这句话是关键,加上它,可以保证盒子的宽,高,不增加 } .child{ width: 200px; height: 100px; background: }
|
第二种居中方法如下:
1 2 3 4 5 6 7 8 9
| //该方法只在子元素宽高已知的情况下用 .child{ width: 200px; height: 100px; background: position: relative; left:100px; top:50px; }
|
第三种居中方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| //这个方法常用 .parent{ width: 400px; height: 200px; background: red; position: relative; } .child{ width: 200px; height: 100px; background: position: absolute; left:50%; top:50%; margin-top:-50px; margin-left:-100px; }
|
第四种居中方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| .parent{ overflow: hidden; //加border:1px solid transparent也是可以的,决绝外边距合并问题,就是防止大盒子也会谁着小盒子往下移动 width: 400px; height: 200px; background: red; } .child{ width: 200px; height: 100px; background: margin-top: 50px; margin-left: 100px; }
|
第五种居中方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| //注意:这个方法,对底版的IE不兼容 .parent{ width: 400px; height: 200px; background: red; display: table-cell; vertical-align:middle; } .child{ width: 200px; height: 100px; background: margin: 0px auto; }
|
第六种居中方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| //注意:这个方法,对底版的IE兼容 .parent{ width: 400px; height: 200px; background: red; display: table-cell; vertical-align:middle; text-align: center; } .child{ width: 200px; height: 100px; background: display: inline-block; }
|
第七种居中方法如下:
1 2 3 4 5 6 7 8 9 10 11 12
| .parent{ width: 400px; height: 200px; background: red; display:flex; } .child{ width: 200px; height: 100px; background: margin: auto; }
|
第八种居中方法如下:
1 2 3 4 5 6 7 8 9
| //注意:这个方法,有兼容问题 .parent{ width: 400px; height: 200px; background: red; display:flex; justify-content: center; align-items: center; }
|
第九种居中方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| .parent{ width: 400px; height: 200px; background: red; position: relative; } .child{ width: 200px; height: 100px; background: position: absolute; top:50%; left:50%; transform: translate(-50%,-50%); }
|