2.任意元素垂直水平居中(多种方法)

书诚小驿2024/10/01前端面经JavaScript

任意元素垂直水平居中(多种方法)

提示

DETAILS
  1. 使用 Flex 弹性布局
  2. 使用 Grid 网格布局
  3. vertical-align: center;line-height: height;
  4. 子绝父相对定位

答案

DETAILS
  1. 使用 Flex 弹性布局
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
  1. 使用 Grid 网格布局
.parent {
  display: grid;
  place-items: center; /* 这是 justify-items: center; 和 align-items: center; 的简写 */
  height: 100vh; /* 或者其他你需要的高度,确保父元素有足够的空间来居中子元素 */
}
  1. vertical-align: center;line-height: height;
.parent {
  width: 100%;
  height: 100px;
  vertical-align: center;
  line-height: 100px;
}
  1. 子绝父相对定位
.parent {
  position: relative;
  height: 100px;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
最后更新时间' 2025/2/26 01:16:20