頁面設計中,常常須要實現元素的水平垂直居中,css實現的方法有不少(列如: margin: auto、position定位、css表達式calc()、使用css預處理、table等均可以實現水平居中),但大多都是針對容器高度不固定,元素高度固定的狀況。css
這裏咱們介紹幾種實現容器寬高和元素寬高都不固定的狀況實現水平垂直居中html
github代碼片斷地址: https://github.com/haozhaohang/library/tree/master/%E6%B0%B4%E5%B9%B3%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%ADdemogit
1、flex實現水平垂直居中github
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>實現未知高度的垂直居中</title> 5 6 <style> 7 html, body { 8 height: 100%; 9 } 10 11 .containers { 12 width: 100%; 13 height: 100%; 14 display: flex; 15 justify-content: center; 16 align-items: center; 17 } 18 </style> 19 20 </head> 21 <body> 22 <div class="containers"> 23 <span>flex實現垂直居中</span> 24 </div> 25 </body> 26 </html>
容器設置display: flex;瀏覽器
容器內的元素設置 jusify-content: center;實現水平居中flex
align-items: center; 實現垂直居中 spa
2、grid實現水平垂直居中(這多是實現水平垂直居中最簡單的css樣式)設計
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>實現未知高度的垂直居中</title> 5 6 <style> 7 html, body { 8 height: 100%; 9 } 10 11 .containers { 12 height: 100%; 13 display: grid; 14 } 15 16 span { 17 margin: auto; 18 } 19 </style> 20 21 </head> 22 <body> 23 <div class="containers"> 24 <span>grid實現垂直居中(許這是最簡潔的水平垂直居中的 CSS 樣式)</span> 25 </div> 26 </body> 27 </html>
目前瀏覽器的支持率,可是能夠用在內部的管理系統,在指定的瀏覽器上運行code
容器設置 display: grid;htm
容器元素設置 margin: auto; 實現水平垂直居中