我们在学习CSS过程中,肯定会用到如何让元素垂直居中,今天我就总结一些常见的CSS垂直居中的方法吧。
1.行高line-height
让文字垂直居中最简单的方法就是首先设置文字的行高等于盒子的高度,这样可以让文字垂直居中在盒子里,然后利用text-aline: center方法使文字水平居中于盒子中。
div {
width:200px;
height: 100px;
background-color: chocolate;
text-align: center;
line-height: 100px;
}
2.使用position + transform: translate(-50%,-50%)
这个方法需要设置父盒子为相对定位,子盒子为绝对定位,然后子盒子的定位设置为:left: 50%;top:50%;使子盒子位于中心左侧和中心右侧。再利用水平位移transform到自身宽高的一半(负)就可以水平和垂直居中了。
.parent {
position: relative;
width: 300px;
height: 200px;
background-color: brown;
}
.child {
position: absolute;
width: 100px;
height: 60px;
background-color: blueviolet;
left: 50%;
top:50%;
transform: translate(-50%, -50%);
}
3.position+margin减去子元素宽高的一半实现
上半部分与第二个方法一致,下半部分利用子盒子的margin-top与margin-left分别减去子盒子宽高的一半就可以垂直居中。
.child {
position: absolute;
width: 100px;
height: 60px;
background-color: blueviolet;
left: 50%;
top: 50%;
margin-top: -30px;
margin-left: -50px;
}
4.使用position+margin:auto实现
利用绝对定位top: 0;left: 0;bottom: 0;right: 0;使子元素充满整个容器,这时候使用margin: auto;就能使元素居中啦。这个方法需要给子元素设置高度。
.child {
position: absolute;
width: 100px;
height: 60px;
background-color: blueviolet;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
5.flex垂直居中(父flex,子margin)
父元素设置**display: flex;然后子元素使用margin:auto auto;**就可以实现居中了。
.parent {
width: 300px;
height: 200px;
background-color: brown;
display: flex;
}
.child {
width: 100px;
height: 60px;
background-color: blueviolet;
margin: auto auto;
}
6.flex垂直居中(父align-items与justify-content)
这个方法需要设置父元素flex布局,然后将align-items改为center即可实现垂直居中,将justify-content改为center即可实现水平居中,即使子元素高度不确定的情况下也可以使用该方法。
.parent {
width: 300px;
height: 200px;
background-color: brown;
display: flex;
/* 垂直居中 */
align-items: center;
/* 水平居中 */
justify-content: center;
}
7.grid垂直居中(父grid,子align-self与justify-self)
父元素设置grid网格布局,使得子元素可以使用网格定位。子元素align-self 和 justify-self都设置为center 用于控制子元素在网格单元格中的对齐方式为垂直居中和水平居中。
.parent {
width: 300px;
height: 200px;
background-color: brown;
display: grid;
}
.child {
width: 100px;
height: 60px;
background-color: blueviolet;
/* 垂直居中 */
align-self: center;
/* 水平居中 */
justify-self: center;
}