CSS垂直居中元素:3种常用方法详解
有多种方法可以在CSS中垂直居中元素,以下是其中几种常见的方法:
- 使用flexbox布局:
.container {
display: flex;
align-items: center;
justify-content: center;
}
将要垂直居中的元素放在一个具有display: flex;属性的父容器中,并使用align-items: center;和justify-content: center;将元素在容器中垂直居中。
- 使用绝对定位和transform属性:
.container {
position: relative;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
将要垂直居中的元素放在一个具有position: relative;属性的父容器中,然后使用position: absolute;、top: 50%;、left: 50%;和transform: translate(-50%, -50%);将元素在容器中垂直居中。
- 使用表格布局:
.container {
display: table;
}
.centered {
display: table-cell;
vertical-align: middle;
}
将要垂直居中的元素放在一个具有display: table;属性的父容器中,然后使用display: table-cell;和vertical-align: middle;将元素在容器中垂直居中。
这些方法都可以实现垂直居中,选择适合你的情况的方法即可。
原文地址: https://www.cveoy.top/t/topic/qjhf 著作权归作者所有。请勿转载和采集!