让一个元素水平垂直居中的方式

  1. 定位+margin
javascript 复制代码
<style>
*{
  margin: 0;
  padding: 0;
}
.father{
  width: 400px;
  height: 400px;
  border: 1px solid;
  position: relative;
}
.son{
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: red;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}
</style>
<body>
<div class="father">
  <div class="son"></div>
</div>
<body>
  1. 定位+transform
javascript 复制代码
<style>
.father{
  width: 400px;
  height: 400px;
  border: 1px solid;
  position: relative;
}
.son{
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: blue;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
<body>
<div class="father">
  <div class="son"></div>
</div>
<body>
  1. flex
javascript 复制代码
<style>
.father{
  width: 400px;
  height: 400px;
  border: 1px solid;
  display: flex;
  align-item: center;
  justify-content: center;
}
.son{
  width: 200px;
  height: 200px;
  background-color: pink;
}
</style>
<body>
<div class="father">
  <div class="son"></div>
</div>
<body>
  1. grid布局
  2. table布局
相关推荐
是乐谷6 分钟前
阿里云杭州 AI 产品法务岗位信息分享(2025 年 8 月)
java·人工智能·阿里云·面试·职场和发展·机器人·云计算
uhakadotcom6 分钟前
开源:subdomainpy快速高效的 Python 子域名检测工具
前端·后端·面试
爱加班的猫14 分钟前
Node.js 中 require 函数的原理深度解析
前端·node.js
用户81651112639715 分钟前
WWDC 2025 Build a SwiftUI app with the new design
前端
伍哥的传说19 分钟前
Vue 3.5重磅更新:响应式Props解构,让组件开发更简洁高效
前端·javascript·vue.js·defineprops·vue 3.5·响应式props解构·vue.js新特性
阅文作家助手开发团队_山神22 分钟前
第一章: Mac Flutter Engine开发准备工作
前端·flutter
菜牙买菜24 分钟前
Hicharts入门
前端·vue.js·数据可视化
摸着石头过河的石头30 分钟前
手把手教你入门 MCP:模型上下文协议与 Trae IDE 中的实践
前端·mcp
德育处主任30 分钟前
p5.js 3D 形状 "预制工厂"——buildGeometry ()
前端·javascript·canvas