CSS的水平垂直居中在日常开发中是用得是非常多的,几乎无处不在的存在,因此在此举例了七种方法
目录
一、单行
1、line-height + text-align
HTML
<div class="box">line-height + text-align</div>
CSS
.box {
width: 400px;
height: 200px;
line-height: 200px; /* 垂直居中 */
text-align: center; /* 水平居中 */
color: #ffffff;
background-color: #FF6666;
}
效果
二、多行
1、flex
HTML
<div class="parent">
<div class="child">flex</div>
</div>
CSS
.parent {
width: 400px;
height: 200px;
color: #ffffff;
background-color: #FF6666;
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
.child {
width: 200px;
height: 100px;
line-height: 100px;
text-align: center;
background-color: #0066FF;
}
效果
2、flex + column
HTML
<div class="parent">
<div class="child">flex column</div>
</div>
CSS
.parent {
width: 400px;
height: 200px;
color: #ffffff;
background-color: #FF6666;
display: flex;
flex-direction: column; /* 垂直方向,默认是水平方向 row */
align-items: center; /* 水平居中 */
justify-content: center; /* 垂直居中 */
}
.child {
width: 200px;
height: 100px;
line-height: 100px;
text-align: center;
background-color: #0066FF;
}
效果
3、grid
HTMl
<div class="parent">
<div class="child">grid</div>
</div>
CSS
.parent {
width: 400px;
height: 200px;
color: #ffffff;
background-color: #FF6666;
display: grid;
place-items: center; /* align-items: center 和 justify-items: center 的简写 */
}
.child {
width: 200px;
height: 100px;
line-height: 100px;
text-align: center;
background-color: #0066FF;
}
效果
4、父相子绝 + transform
HTML
<div class="parent">
<div class="child">父相子绝 + transform</div>
</div>
CSS
.parent {
width: 400px;
height: 200px;
color: #ffffff;
background-color: #FF6666;
position: relative;
}
.child {
width: 200px;
height: 100px;
line-height: 100px;
text-align: center;
background-color: #0066FF;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
效果
5、父相子绝 + margin:auto
HTML
<div class="parent">
<div class="child">父相子绝 + margin:auto</div>
</div>
CSS
.parent {
width: 400px;
height: 200px;
color: #ffffff;
background-color: #FF6666;
position: relative;
}
.child {
width: 200px;
height: 100px;
line-height: 100px;
text-align: center;
background-color: #0066FF;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
效果
6、table-cell
HTML
<div class="parent">
<div class="child">table-cell</div>
</div>
CSS
.parent {
width: 400px;
height: 200px;
background-color: #FF6666;
display: table-cell;
vertical-align: middle;
}
.child {
width: 200px;
height: 100px;
line-height: 100px;
text-align: center;
background-color: #0066FF;
margin: auto;
}