如何在 CSS 中实现 div 内容垂直居中显示

      发布在:前端技术      评论:0 条评论

要让一个 div 块的内容在垂直方向上居中显示,你可以使用多种方法,下面是几种常见的方法:


1. 使用 Flexbox 布局:

.container {
  display: flex;
  align-items: center; /* 在交叉轴上居中 */
  justify-content: center; /* 在主轴上居中 */
}


2. 使用 Grid 布局:

.container {
  display: grid;
  place-items: center; /* 居中元素 */
}


3. 使用绝对定位和 transform 属性:

.container {
  position: relative;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}


4. 使用 display: table-cell 和 vertical-align: middle:

.container {
  display: table-cell;
  vertical-align: middle;
  text-align: center; /* 如果需要水平居中 */
}

以上方法都可以实现垂直居中,具体选择哪种取决于你的项目需求和个人喜好。


热门推荐