记录实现水平垂直居中的5种方法

记录块级元素实现水平垂直居中的方法,效果如图。

html 复制代码
<div class="parent">
  <div class="child">居中元素</div>
</div>


<style>
.parent {
  position: relative;
  width: 600px;
  height: 300px;
  background-color: #679389;
}
.child {
  width: 300px;
  height: 120px;
  background-color: #d8a7a0;
  text-align: center;
  line-height: 120px;
}
</style>

方法1: flex布局。给parent设置center_1。

css 复制代码
.center_1 {
  display: flex;
  justify-content: center;
  align-items: center;
}

方法2: grid布局。设置一个3x3的网格,将子元素放在中间个字中。给parent设置center_2 ,给child设置center_2--child

css 复制代码
.center_2 {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
}
.center_2--child {
  grid-row-start: 2;
  grid-column-start: 2;
}

方法3: absolute+margin矫正偏移。给child设置center_3,此时margin矫正的位置分别是宽高的一半,因此需要知道子元素的宽高。

css 复制代码
.center_3 {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -60px;
  margin-left: -150px;
}

方法4: absolute+transfom矫正偏移。给child设置center_3。

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

方法5: display: table-cell。给parent 设置center_5,此时如果子元素为块级元素,text-align不会生效,可以给子元素child设置display: inline-block。

css 复制代码
.center_5 {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.center_5--child {
  display: inline-block;
}
相关推荐
七牛云行业应用11 分钟前
别每次重复配置了!CLAUDE.md + Hooks 让 Claude Code 开箱就记住你的规则
前端
超人气王17 分钟前
新手学前端 JavaScript 类型判断:一篇彻底搞懂 typeof、instanceof 和 Object.prototype.toString
前端·javascript
LucianaiB25 分钟前
耗时30天,DocPilot Qwen正式开源:一个免费无广的开源文档 AI 助手
前端·后端
xiaoshuaishuai843 分钟前
C# AvaloniaUI 资源找不到报错
java·服务器·前端·windows·c#
How_doyou_do1 小时前
26字节工程营-前端-自我总结
前端
十有八七1 小时前
🧩 组件库死亡倒计时?—— AI 编码冲击下的前端基础设施重构
前端·人工智能
风止何安啊1 小时前
我一个前端仔,居然用 Python 搞起了 AI?从零到一,撸了个 AI 聊天框小 demo
前端·人工智能·后端
GISer_Jing1 小时前
Claude Code插件系统全解析
前端·人工智能·ai·架构
小茴香3531 小时前
Vue3路由权限动态管理
前端·前端框架·vue3
RANxy1 小时前
零基础全栈 React 入门(四):React Router 路由配置
前端·react.js