text-align: center;
margin: auto;
.parent { width: 400px; height: 400px; background-color: aquamarine; text-align: center; } .child { width: 100px; height: 100px; background-color: #43ff26; display: inline-block; }
這樣能夠使一塊級元素擁有一些inline元素的特性。html
.parent {position:relative;}
.child {position:absolute;left:50%;transform:translateX(-50%);}
.parent { width: 400px; height: 400px; background-color: aquamarine; display: flex; justify-content: center; }
.parent {display:table-cell;vertical-align:middle;}
優勢:只需設置父節點,兼容性好佈局
.parent {position:relative;} .child{position:absolute;top:50%;transform:translateY(-50%);}
.parent {display:flex;align-items:center;}
text-align:center+line-heightpost
.parent {text-align:center;display:table-cell;vertical-align:middle;}
.child {display:inline-block;}
.parent {position:relative;}
.child{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);}
.parent {display:flex;justify-content:center;align-items:center;}
<div class="absolute_p1"> <div class="absolute_c1"></div> </div> .absolute_p1 { position: relative; width: 200px; height: 200px; } .absolute_p1 .absolute_c1 { position: absolute; /* fixed 同理 */ left: 50%; top: 50%; width: 100px; height: 100px; margin-left: -50px; margin-top: -50px; /* 需根據寬高計算偏移量 */ }
<div class="absolute_p2"> <div class="absolute_c2"></div> </div> .absolute_p2 { position: relative; width: 200px; height: 200px; } .absolute_p2 .absolute_c2 { position: absolute; /* fixed 同理 */ left: 0; top: 0; bottom: 0; right: 0; /* 定位爲 0 */ width: 100px; height: 100px; margin: auto; /* 不用計算偏移量 */ }
原理: 原理我也不知道啊!估計定位都給0了,元素本身也不知道該去哪兒,只好待在原地不知所措...flex