@H5 让小盒子在大盒子内水平垂直居中的9种方法总结
以下所有方法中的盒子的css样式都为如下代码
body>div{ width:400px; height:400px; background:#0f0; margin-bottom:20px;}
div div{ width:100px; height:100px; background:#ff0; font-size:50px; line-height:100px; text-align:center;}
1
效果如图
1.利用定位(三种方法)
body>div:nth-child(1){ position:relative}
body>div:nth-child(1) div{ position:absolute; top:0; left:0; right:0; bottom:0; margin:auto}
body>div:nth-child(2){ position:relative}
body>div:nth-child(2) div{ position:absolute; top:50%; left:50%; transform:translate(-50%,-50%)}
body>div:nth-child(3){ position:relative}
body>div:nth-child(3) div{ position:absolute; top:50%; left:50%; margin-top:-50px; margin-left:-50px;}
2.利用display(3种方法)
body>div:nth-child(4){ display:flex;}
body>div:nth-child(4) div{ margin:auto}
body>div:nth-child(5){ display:flex; align-items:center; justify-content:center}
body>div:nth-child(6){ display:flex; justify-content:center}
body>div:nth-child(6) div{ align-self:center;}
方法7:
body>div:nth-child(7){ display:table-cell; vertical-align:middle; text-align:center;}
body>div:nth-child(7) div{ display:inline-block;}
方法8: 利用一个span标签
8
body>div:nth-child(8){ text-align:center;}
body>div:nth-child(8) div{ vertical-align:middle; display:inline-block}
body>div:nth-child(8) span{ width:0; height:100%; vertical-align:middle; display:inline-block;}
方法9:
body>div:nth-child(9){ text-align:center; line-height:400px;}
body>div:nth-child(9) div{ vertical-align:middle; display:inline-block}