在開發和面試中經常會遇到垂直居中的問題,下面總結了幾種常見的實現方法:
幾種方法公用的 HTML:
<div class="root">
<div class="item">
</div>
</div>
-
通過
display: flex;
實現:.root { width: 500px; height: 500px; border: 2px solid black; display: flex; justify-content: center; align-items: center; } .item { width: 200px; height: 200px; background-color: brown; }
對彈性布局不了解的小伙伴可以參考另一篇文章:Flex 布局(彈性盒子、彈性布局)
-
通過
display: table-cell;
實現:.root { width: 500px; height: 500px; border: 2px solid black; display: table-cell; text-align: center; vertical-align: middle; } .item { width: 200px; height: 200px; background-color: brown; display: inline-block; }
-
通過
margin
+transform
實現:.root { width: 500px; height: 500px; border: 2px solid black; /*防止外邊距塌陷,解決辦法:父元素加上邊框或overflow: hidden;*/ } .item { width: 200px; height: 200px; background-color: brown; margin: 50% auto; transform: translateY(-50%); }
-
通過
inline-block
+vertical-align
實現:.root { width: 500px; height: 500px; border: 2px solid black; line-height: 500px; text-align: center; } .item { width: 200px; height: 200px; background-color: brown; display: inline-block; vertical-align: middle; }
-
通過
absolute
+負margin
實現:.root { width: 500px; height: 500px; border: 2px solid black; position: relative; } .item { width: 200px; height: 200px; background-color: brown; position: absolute; left: 50%; top: 50%; margin-top: -100px; margin-left: -100px; }
-
通過
absolute
+margin: auto;
實現:.root { width: 500px; height: 500px; border: 2px solid black; position: relative; } .item { width: 200px; height: 200px; background-color: brown; position: absolute; left: 0; top: 0; bottom: 0; right: 0; margin: auto; }
-
通過
absolute
+transform
實現:.root { width: 500px; height: 500px; border: 2px solid black; position: relative; } .item { width: 200px; height: 200px; background-color: brown; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
原文鏈接:8種垂直居中的方法