一說(shuō)到水平居中们豌,立馬會(huì)想到text-align: center或者margin: auto宵睦,很容易就實(shí)現(xiàn)了记罚。然而,要實(shí)現(xiàn)垂直居中時(shí)壳嚎,就沒(méi)那么簡(jiǎn)單了桐智。
下面簡(jiǎn)單介紹所了解到的幾種方法。
// html
<div class="outer">
<div class="inner"></div>
</div>
個(gè)人經(jīng)常用到的兩種方法:
.outer {
position: relative;
width: 500px;
height: 400px;
background: #ccc;
}
.inner {
width: 200px;
height: 200px;
background: #aaa;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.outer {
position: relative;
width: 500px;
height: 400px;
background: #ccc;
}
.inner {
width: 200px;
height: 200px;
background: #aaa;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
比較少用到诬辈,或者說(shuō)基本不會(huì)這么寫(xiě)的兩種方法:
.outer {
position: relative;
width: 500px;
height: 400px;
background: #ccc;
}
.inner {
width: 200px;
height: 200px;
background: #aaa;
position: absolute;
top: calc(50% - 100px); /* 200/2 = 100 */
left: calc(50% - 100px); /* 200/2 = 100 */
}
.outer {
position: relative;
width: 500px;
height: 400px;
background: #ccc;
}
.inner {
width: 200px;
height: 200px;
background: #aaa;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px; /* 200/2 = 100 */
margin-left: -100px; /* 200/2 = 100 */
}
flex,現(xiàn)在很多瀏覽器也都支持這個(gè)屬性了荐吉,更少的代碼焙糟。
.outer {
width: 500px;
height: 400px;
background: #ccc;
display: flex;
align-items: center;
justify-content: center;
}
.inner {
width: 200px;
height: 200px;
background: #aaa;
}