1 前言
水平居中、垂直居中是前端面试百问不厌的问题。其实现方案也是多种多样,常叫人头昏眼花。
水平方向可以认为是内联方向,垂直方向认为是块级方向。
2 内联元素的水平垂直居中
首先,常见内联元素有:a、span、em、b、strong、i、button。
<div class="container">
<span class="innerText">Hello,World!</span>
</div>
2.1 display: flex
.container {
height: 100px;
width: 200px;
background-color: cadetblue;
display: flex;
/* 水平居中 */
justify-content: center;
/* 垂直居中 */
align-items: center;
}
2.2 text-align+line-hight
.container {
height: 100px;
width: 200px;
background-color: antiquewhite;
/* 水平居中 */
text-align: center;
/* 垂直居中,行高等于高度 */
line-height: 100px;
}
2.3 text-align+display: table-cell
.container {
height: 100px;
width: 200px;
background-color: antiquewhite;
display: table-cell;
/* 水平居中 */
text-align: center;
/* 垂直居中 */
vertical-align: middle;
}
2.4 display: grid
.container {
height: 100px;
width: 200px;
background-color: antiquewhite;
display: grid;
place-items: center;
}
place-items是align-items、justify-items的简写。
3 块级元素的水平垂直居中
常见块级元素有:h1-h6、p、div、ul、ol、li等。
<div class="container">
<div class="innerText"></div>
</div>
前面介绍的内联元素的水平垂直居中方法也适用于块级元素。下面就不再重复介绍。
3.1 定位+间距的多种组合
.container {
height: 100px;
width: 200px;
background-color: cadetblue;
position: relative;
}
.innerText {
background-color: black;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 50px;
height: 50px;
/* 水平垂直居中 */
margin: auto;
}
.container {
height: 100px;
width: 200px;
background-color: cadetblue;
position: relative;
}
.innerText {
width: 50px;
height: 50px;
background-color: black;
position: absolute;
top: 50%;
left: 50%;
margin: -25px 0 0 -25px;
}
.container {
height: 100px;
width: 200px;
background-color: cadetblue;
position: relative;
}
.innerText {
width: 50px;
height: 50px;
background-color: black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}