這類問題是面試中經常出現的css問題。那么你會嗎?會的話,你能想出幾種解決方案呢?我這里大致列舉六個方法!
1.彈性盒模型flex布局
<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; display: flex; justify-content: center; /*主軸居中對齊*/ align-items: center; /*交叉軸即y方向劇中對齊*/ } .box{ width: 333px; height: 333px; background: blue; } </style> </head> <body> <div class="wrap"> <div class="box"></div> </div> </body>
2.利用偽類來對齊
<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; text-align: center; } .wrap:after{ display: inline-block; content: ''; height: 100%; /*width:0;*/ vertical-align: middle; } .box{ width: 333px; height: 333px; background: blue; display: inline-block; vertical-align: middle; } </style> </head> <body> <div class="wrap"> <div class="box"></div> </div> </body>
3.利用空span,原理與上面的類似
<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; text-align: center; } span{ display: inline-block; height: 100%; vertical-align: middle; } .box{ width: 333px; height: 333px; background: blue; display: inline-block; vertical-align: middle; } </style> </head> <body> <div class="wrap"> <div class="box"></div><span></span> </div> </body>
4.利用表格的特性:單元表格的內容默認垂直居中
<style type="text/css">
.wrap{ width:500px; height: 500px; background: red; text-align: center;
border-collapse: collapse;
} .box{ width: 333px; height: 333px; background: blue; display: inline-block; /*margin: 0 auto;*/ /*或者*/ } </style> </head> <body> <table class="wrap"> <td><div class="box"></div></td> </table> </body>
5.將塊標簽轉換成表格屬性,display:table-cell
<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; display: table-cell; text-align: center; vertical-align: middle; } .box{ width: 333px; height: 333px; background: blue; display: inline-block; vertical-align: middle; } </style> </head> <body> <div class="wrap"> <div class="box"></div> </div> </body>
6.利用相對定位和transform
<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; /*display: table-cell;*/ /*text-align: center;*/ } .box{ width: 333px; height: 333px; background: blue; position: relative;//不脫離文檔流,left,top移動父級的百分之五十 left: 50%; top: 50%; -webkit-transform: translateX(-50%) translateY(-50%)//即使未知元素自身寬高,自動計算后x,y軸移動元素自身寬高的負百分之五十 } </style> </head> <body> <div class="wrap"> <div class="box"></div> </div> </body>
總結:span和偽類對齊方法主要是利用了空內容將基線定在了父級元素的中間位置,然后用inline-block結合vertical-align:middle. table的2種方法則是利用了表格的自帶屬性,彈性盒模型的話就不用多說了,強大的愛不釋手,
transform和相對定位結合處理的話,因為要依據父級寬高所以用相對定位,用絕對定位的話會一層層找到頂級,transform再根據自身寬高負方向移動半個寬高。
關於基線對准問題可參考張鑫旭老師的博客,寫的非常詳細,可自行百度。
關於彈性盒模型的參數介紹可查看文檔或者是阮一峰老師的博客。