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

  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布局
相关推荐
matrixmind82 分钟前
sindresorhustype-fest:TypeScript 工具类型集合
前端·javascript·其他·typescript
通往曙光的路上9 分钟前
JUCJUCJUC
java·前端·数据库
Swift社区11 分钟前
鸿蒙 PC vs Web:谁才是未来应用形态?
前端·华为·harmonyos
问心无愧051312 分钟前
ctf show web入门54
前端·笔记
西贝爱学习19 分钟前
pdf转TXT文本,适用于文字型PDF;扫描版PDF需要使用OCR(光学字符识别)技术来识别图中的文字
java·服务器·前端
故事和你9122 分钟前
洛谷-【数据结构2-2】线段树1
开发语言·javascript·数据结构·算法·动态规划·图论
ZC跨境爬虫22 分钟前
跟着 MDN 学 HTML day_43:(DocumentFragment 接口详解)
前端·javascript·vue.js·ui·html·音视频
Bigger34 分钟前
mini-cc:用最小的代码,复刻一个“真正能干活”的 AI 编程智能体(并且把架构讲清楚)
前端·ai编程·claude
问心无愧051337 分钟前
ctf show web 入门46
android·前端·笔记
ooseabiscuit41 分钟前
PHP与C++:Web与系统编程的终极对决
前端·c++·php