本文是对三个月前《CSS 加油包之垂直居中》的更正和添增,由于本文中没有实例,所以保留了旧文,地址⬇️
为什么垂直居中不好做?
与 CSS 的回溯机制有关;由于 CSS 不正交,调节单个属性的时候,别的属性可能也会随之变化。
1. 不知道自己的高度和父元素的高度
parentElement{
position: relative;
}
childElement{
position: absolute;
top: 50%;
transform: translateY(-50%) /* 也可以写成 translate(0, 50%) */
}
2. 如果父容器下只有一个元素,且高度已设置,可以给子元素用相对定位
parentElement{
height: xxx;
}
childElement {
position: relative;
top: 50%;
transform: translateY(-50%)
}
3. 如果父容器的高度已设置,还可以用 margin: auto;
parentElement{
position: relative;
width: xxx;
height: xxx;
}
childElement{
position: absolute;
width: xxx;
height: xxx;
top: 0;
bottom: 0;
margin: auto;
}
4. 不考虑兼容老式浏览器的话,父容器可以用 flex 布局
parentElement{
display: flex;
display: -webkit-flex; /* Safari compatible */
align-items: center; /* 指定垂直居中 */
}
5. flex 布局的另一种方法 flex-direction: column;
parentElement{
display: flex;
flex-direction: column;
justify-content: center;
width: xxx;
height: xxx;
}
childElement{
width: xxx;
height: xxx;
}
6. 父容器用 display: table;
parentElement{
display: table;
}
childElement{
display: table-cell;
vertical-align: middle;
}
7. 父容器用 display: grid; 再设置两个辅助元素
parentElement{
display: grid;
width: xxx;
height: xxx;
}
.targetChild{
background: xxx;
}
.aboveTarget, .belowTarget {
background: yyy;
}