一说到水平居中,立马会想到text-align: center或者margin: auto,很容易就实现了。然而,要实现垂直居中时,就没那么简单了。
下面简单介绍所了解到的几种方法。
// html
<div class="outer">
<div class="inner"></div>
</div>
个人经常用到的两种方法:
.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;
}
比较少用到,或者说基本不会这么写的两种方法:
.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,现在很多浏览器也都支持这个属性了,更少的代码。
.outer {
width: 500px;
height: 400px;
background: #ccc;
display: flex;
align-items: center;
justify-content: center;
}
.inner {
width: 200px;
height: 200px;
background: #aaa;
}