水平居中
對于行內(nèi)元素: 在其父元素上使用
text-align: center
-
對于定寬的塊級元素:
margin-left: auto; margin-right: auto
.content { width: 100px; position: absolute; left: 50%; margin-left: -50px; }
.content { width: 100px; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; }
-
對于寬度不定的塊級元素
.content { position: absolute; left: 50%; transform: translateX(-50%); /* 移動元素本身50% */ }
-
相對定位實現(xiàn)水平居中
用float或者display把父元素變成行內(nèi)塊狀元素.parent { display: inline-block; /* 把父元素轉(zhuǎn)化為行內(nèi)塊狀元素 */ /*float: left; 把父元素轉(zhuǎn)化為行內(nèi)塊狀元素 */ position: relative; left: 50%; } /*目標元素*/ .content { position: relative; right: 50%; }
-
CSS3的flex實現(xiàn)水平居中方法
.parent { display: flex; flex-direction: column; } .content { align-self: center; }
.parent { display: flex; } .content { margin: auto; }
.parent { display: flex; justify-content: center; }
-
CSS3的fit-content配合左右margin為auto實現(xiàn)水平居中方法
.content { width: fit-content; margin-left: auto; margin-right: auto; }
table標簽配合margin左右auto實現(xiàn)水平居中
使用table標簽(或直接將塊級元素設(shè)值為display:table),再通過給該標簽添加左右margin為auto(不推薦使用table慌申,違反語義化)inline-block實現(xiàn)水平居中方法
display:inline-block;(或display:inline)和text-align:center;
實現(xiàn)水平居中(這種方法有問題枚钓,不推薦,因為inline-block元素之間會有空隙栓霜,可以用負margin解決)
垂直居中
關(guān)于垂直居中大诸,最好的方式就是父元素不給定高度十厢,則只需要使用padding: npx 0
就可以實現(xiàn)垂直居中
如果父元素給定了高度,則:
-
使用table的特性
<table class="parent"> <tr> <td class="child"> xxx </tr> </table>
-
可以將標簽偽裝為table
<div class="table"> <div class="td"> <div class="child"> xxx </div> </div> </div>
div.table { display: table; height: 400px; } div.tr { display: table-row; } div.td { display: table-cell; vertical-align: middle; } .child { border: 10px solid black; }
-
絕對定位
.parent { height: 400px; position: relative; } .content { height: 100px; position: absolute; top: 50%; margint-top: -50px; }
.parent { height: 400px; position: relative; } .content { position: absolute; top: 50%; transform: translateY(-50%); }
.parent { height: 600px; position: relative; } .child { position: absolute; height: 200px; top: 0; bottom: 0; left: 0; right: 0; margin: auto; }
-
flex
.parent { height: 400px; display: flex; align-items: center; } .content { width: 300px; }
-
100%高度的after before加上 inline-block
.parent { height: 400px; text-align: center; } .content { display: inline-block; width: 200px; vertical-align: middle; } .parent:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; } .parent:after { content: ''; display: inline-block; height: 100%; vertical-align: middle; }