1.利用line-height實現居中,這種方法適合純文字類的;css
<!-- css --> <style> .parents { height: 400px; line-height: 400px; width: 400px; border: 1px solid red; text-align: center; } .child { background-color: blue; color: #fff; } </style> </head> <body> <!-- html --> <div class="parents"> <span class="child">css佈局,實現垂直居中</span> </div> </body>
2.經過設置父容器相對定位,子級設置絕對定位,標籤經過margin實現自適應居中;html
<!-- css --> <style> .parents { height: 400px; width: 400px; border: 1px solid red; position: relative; } .child { width: 200px; height: 100px; line-height: 100px; text-align: center; color: #fff; background-color: blue; /* 四個方向設置爲0, 而後經過margin爲auto自適應居中 */ position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; } </style> </head> <body> <!-- html --> <div class="parents"> <span class="child">css佈局,實現垂直居中</span> </div> </body>
3.彈性佈局flex 父級設置display: flex; 子級設置margin爲auto實現自適應居中;佈局
<!-- css --> <style> .parents { height: 400px; width: 400px; border: 1px solid red; display: flex; } .child { width: 200px; height: 100px; line-height: 100px; text-align: center; color: #333; background-color: yellow; margin: auto; } </style> </head> <body> <!-- html --> <div class="parents"> <span class="child">css佈局,實現垂直居中</span> </div> </body>
4. 父級設置相對定位,子級設置絕對定位,而且經過位移transform實現;flex
<!-- css --> <style> .parents { height: 400px; width: 400px; border: 1px solid red; position: relative; } .child { width: 200px; height: 100px; line-height: 100px; text-align: center; color: #fff; background-color: green; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> </head> <body> <!-- html --> <div class="parents"> <span class="child">css佈局,實現垂直居中</span> </div> </body>
5. 父級設置彈性盒子,並設置彈性盒子相關屬性;spa
<!-- css --> <style> .parents { height: 400px; width: 400px; border: 1px solid red; display: flex; justify-content: center; /* 水平 */ align-items: center; /* 垂直 */ } .child { width: 200px; height: 100px; color: black; background-color: orange; } </style> </head> <body> <!-- html --> <div class="parents"> <span class="child"></span> </div> </body>
6. 網格佈局,父級經過轉換成表格形式,而後子級設置行內或行內塊實現。(須要注意的是:vertical-align: middle使用的前提條件是內聯元素以及display值爲table-cell的元素)。code
<!-- css --> <style> .parents { height: 400px; width: 400px; border: 1px solid red; display: table-cell; text-align: center; vertical-align: middle; } .child { width: 200px; height: 100px; color: #fff; background-color: blue; display: inline-block; /* 子元素設置行內或行內塊 */ } </style> </head> <body> <!-- html --> <div class="parents"> <span class="child"></span> </div> </body>