css 水平垂直居中那些事
本文是在參考眾大神文章基礎上,整理的幾個常用方案,另外也摻雜個人的一些猜想,如有不妥,請不吝指出
下面開始正題,為了方便驗證+展示,下面的案例我會直接附上個人驗證的源碼+截圖
1.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css">.container{position:relative;width:500px;height:500px;border:1px solid blue;}.cnt {position: absolute;margin:auto; width:200px;height:200px;border:1px solid red;left:0;right:0;top:0;bottom:0;} </style> </head> <body> <div class="container"> <div class="cnt"></div> </div> </body> </html> </pre> <code> <pre> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> .container{ position:relative; width:500px; height:500px; border:1px solid blue; } .cnt { position: absolute; margin:auto; width:200px; height:200px; border:1px solid red; left:0; right:0; top:0; bottom:0;} </style> </head> <body> <div class="container"><div class="innerCnt"></div> </div> </body> </html>
(所有實例運行效果圖,均類似右圖,下面就不在粘圖了(筆者太懶。。。。))
?這個案例主要應用了兩個div,container和innerCnt組成,子div設成,固定寬高(非auto即可)、絕對定位(absolute)、top/right/bottom/left都設為0才能實現水平垂直居中的效果:
下面是本人猜測:在絕對定位情況下,如果沒有設置坐標值(上右下左的距離),則默認吸附父容器左上角,但同時設置了上右下左的距離為等值的情況下相當于四個人同時朝這四個方向一起在拉繩子,當用相同的力量是達到了一個平衡態,使得容器得以水平垂直居中顯示...233我太有才了這都想得出來
?
2.
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <style type="text/css"> 7 .container{ 8 display:table-cell; //以表格形式布局 9 width: 500px; 10 height: 500px; 11 vertical-align: middle; //垂直居中 12 text-align: center; //水平居中 13 border: 1px solid #000000; 14 } 15 16 .innerCnt{ 17 display:inline-block; 18 width: 200px; 19 height: 200px; 20 border: 1px solid #FF0000; 21 } 22 </style> 23 </head> 24 <body> 25 <div class="container"> 26 <div class="innerCnt"></div> 27 </div> 28 </body> 29 </html>?
這個例子主要展示的是table-cell的應用?
| table-cell | 此元素會作為一個表格單元格顯示(類似 <td> 和 <th>) | 
使得整個區塊作為一個單元格,通過vitical-align來控制垂直居中,text-align控制水平居中(需要注意的是子元素應該設置為inline-block來作為行內區塊)。
?
3.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> .container{text-align: center;width: 500px;height: 500px;border:1px solid blue; } .empty{width:100%;height:50%;margin-bottom:-100px; //計算所得; =innerCnt.height/2 } .innerCnt{display: inline-block;width: 200px;height: 200px;border:1px solid red; } </style> </head> <body> <div class="container"><div class="empty"><!--空的內容--></div><div class="innerCnt">hello</div> </div> </body> </html>?
?
利用一個空div來占位,然后通過margin-bottom來占位使得下方元素上提,實現元素的水平(text-align:center)垂直居中。
?
轉載于:https://www.cnblogs.com/V-JACK/p/5297552.html
總結
以上是生活随笔為你收集整理的css 水平垂直居中那些事的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: spring的service不启动事务的
- 下一篇: HiTool工具烧录uImage过程
