【前端 | CSS系列】—— 第1篇:如何实现水平垂直居中对齐?

五种方法实现水平垂直居中对齐

  • [1. 使用【Flex 布局】](#1. 使用【Flex 布局】)
  • [2. 使用【Grid 布局】](#2. 使用【Grid 布局】)
  • [3. 使用【Table 布局】](#3. 使用【Table 布局】)
  • [4. 使用【绝对定位】+ 【transform 属性】](#4. 使用【绝对定位】+ 【transform 属性】)
  • [5. 使用【绝对定位】+ 【margin 属性】 ------(仅适用于:已知元素宽高)](#5. 使用【绝对定位】+ 【margin 属性】 ——(仅适用于:已知元素宽高))

1. 使用【Flex 布局】

css 复制代码
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

2. 使用【Grid 布局】

css 复制代码
.container {
  display: grid;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

3. 使用【Table 布局】

css 复制代码
.container {
  display: table;
}
.child {
  display: table-cell;
  text-align: center; /* 水平居中 */
  vertical-align: middle; /* 垂直居中 */
}

4. 使用【绝对定位】+ 【transform 属性】

css 复制代码
.container {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

5. 使用【绝对定位】+ 【margin 属性】 ------(仅适用于:已知元素宽高)

css 复制代码
.container {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px; /* 其中50px是元素宽高的一半 */
}

单纯的元素左右居中 对齐:
块级元素 可以使用 magrin: 0 auto;
非块级元素 使用 text-align: center;

相关推荐
柳杉20 分钟前
Three.js × Blender:从建模到 Web 3D 的完整工作流深度解析
前端·javascript·数据可视化
reembarkation1 小时前
vue3中使用howler播放音频列表
前端·vue.js·音视频
手握风云-1 小时前
基于 Java 的网页聊天室(三)
服务器·前端·数据库
weixin199701080162 小时前
《识货商品详情页前端性能优化实战》
前端·性能优化
Forever7_2 小时前
重磅!Vue3 手势工具正式发布!免费使用!
前端·前端框架·前端工程化
用户806138166592 小时前
发布为一个 npm 包
前端·javascript
树上有只程序猿2 小时前
低代码何时能出个“秦始皇”一统天下?我是真学不动啦!
前端·后端·低代码
TT_哲哲2 小时前
小程序双模式(文件 / 照片)上传组件封装与解析
前端·javascript
菜果果儿2 小时前
Vue 3 + TypeScript 常用代码示例总结
前端
前端付豪3 小时前
实现多角色模式切换
前端·架构