百度總結的垂直居中方法
阿新 • • 發佈:2017-10-01
blog http transform gin margin doc otto mage 寬高
一 絕對定位與負邊距
<!--兼容性不錯,缺陷就是必須提前知道被居中塊級元素的大小-->
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>絕對定位與負邊距</title> <style> .box { width: 300px; height: 300px; background: #ccc; position: relative; } .child { width: 150px; height: 100px; background: lawngreen; position: absolute; top: 50%; margin: -50px 0 0 0; /*50px為child高度的一半*/ line-height: 100px; } </style> </head> <body> <div class="box"> <div class="child">蝸牛小</div> </div> </body> </html>
二 使用絕對定位和transform
<!--不必提前知道被居中元素的尺寸了,translate偏移的百分比就是相對於元素自身的尺寸而言-->
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用絕對定位和transform</title> <style> .box { width: 300px; height: 200px; background: lightpink; position: relative; } .child { background: springgreen; position: absolute; top: 50%; transform: translate(0, -50%); } </style> </head> <body> <div class="box"> <div class="child"> 蝸牛小蝸牛小蝸牛小 </div> </div> </body> </html>
三 絕對定位結合margin: auto
<!--居中元素的寬高也可以不設置,但不設置的話就必須是圖片這種自身就包含尺寸的元素, 否則無法實現-->
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>絕對定位結合margin: auto</title> <style> .box { width: 300px; height: 200px; background: lightpink; position: relative; } .child { width: 200px; height: 60px; background: #A1CCFE; position: absolute; top: 0; bottom: 0; margin: auto; line-height: 60px; } </style> </head> <body> <div class="box"> <div class="child">蝸牛小蝸牛小</div> </div> </body> </html>
四 使用flex布局
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用flex布局</title> <style> .box { width: 300px; height: 200px; background: #ddd; display: flex; align-items: center; } .child { width: 300px; height: 60px; background: #8194AA; line-height: 60px; } </style> </head> <body> <div class="box"> <div class="child"> 蝸牛小蝸牛小 </div> </div> </body> </html>
五 使用 line-height 和 vertical-align 對圖片進行垂直居中
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用 line-height 和 vertical-align 對圖片進行垂直居中</title> <style> .box{ width: 300px; height: 200px; background: #ddd; line-height: 200px; } .box img { vertical-align: middle; } </style> </head> <body> <div class="box"> <img src="tip.png" alt="請添加圖片"> </div> </body> </html>
百度總結的垂直居中方法