可以使用以下方法将 div 垂直居中:

  1. 使用 'display: flex' 和 'justify-content'、'align-items' 属性
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}
  1. 使用 'position: absolute' 和 'top'、'left'、'bottom'、'right' 属性
.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
  1. 使用 'display: table-cell' 和 'vertical-align' 属性
.container {
  display: table-cell;
  vertical-align: middle;
}

注意:以上方法都需要将父元素的高度设置为固定值或使用 'min-height' 属性。

CSS Div 垂直居中:3 种常用方法详解

原文地址: https://www.cveoy.top/t/topic/mW8s 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录