兩種浮動元素垂直居中的狀況: 父盒子有寬高; 父盒子沒有寬高
下面時 HTML 中的代碼:
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>浮動元素垂直居中</title> 6 </head> 7 <body> 8 <div class="parent"> 9 <div class="child"></div> 10 </div> 11 </body> 12 </html>
一. 父盒子有寬高:html
垂直居中前代碼實現 :spa
1 .parent { 2 width: 150px; 3 height: 150px; 4 background-color: teal; 5 position: relative; /*注意父盒子要相對定位*/ 6 } 7 .child { 8 width: 50px; 9 height: 50px; 10 background-color: violet; 11 float: left; 12 }
垂直居中前效果圖 :code
垂直居中代碼實現 :htm
1 .parent { 2 width: 150px; 3 height: 150px; 4 background-color: teal; 5 position: relative; /*注意父盒子要相對定位*/ 6 } 7 .child { 8 width: 50px; 9 height: 50px; 10 background-color: violet; 11 float: left; 12 13 position: absolute; 14 top: 50%; /*容器的一半*/ 15 left: 50%; 16 margin-top: -25px; /*子盒子高度的一半*/ 17 margin-left: -25px; /*子盒子寬度的一半*/ 18 }
垂直居中效果圖 :blog
二. 父盒子沒有寬高:
1 .parent { 2 background-color: limegreen; 3 position: relative; 4 } 5 .child { 6 width: 50px; 7 height: 50px; 8 background-color: khaki; 9 float: left; 10 margin: auto; 11 12 position: absolute; 13 top: 0; 14 left: 0; 15 right: 0; 16 bottom: 0; 17 }
因爲父盒子是沒有寬高的, 因此子盒子就相對於頁面中間垂直居中了it