1. 单行文本垂直居中
当元素中只包含单行文本时,将元素的line - height值设置为与元素的height值相等,就可以实现文本的垂直居中:
.text-container {
height: 50px;
line-height: 50px;
border: 1px solid black;
}
2. 块级元素垂直居中(已知高度)
对于已知高度的块级元素,可以将父元素设置为相对定位(position: relative),子元素设置为绝对定位(position: absolute),然后通过设置子元素的top和bottom属性为0,并将margin属性设置为auto来实现垂直居中:
.parent-container {
position: relative; // √
height: 200px;
border: 1px solid black;
}
.child-container {
position: absolute; // √
top: 0; // √
bottom: 0; // √
margin: auto; // √
height: 100px;
border: 1px solid red;
}
3. 块级元素垂直居中(未知高度)
- 使用flex布局
将父元素的display属性设置为flex,并使用align - items: center属性来使子元素在交叉轴(垂直方向)上居中:
.parent-container {
display: flex; // √
align-items: center; // √
height: 300px;
border: 1px solid black;
}
.child-container {
border: 1px solid red;
}
- 使用grid布局
将父元素的display属性设置为grid,然后使用place - items: center实现垂直居中:
.parent-container {
display: grid; // √
place-items: center; // √
height: 400px;
border: 1px solid black;
}
.child-container {
border: 1px solid red;
}