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

  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布局
相关推荐
独立开发之道17 分钟前
【three.js教程】Three.js 材质详解:从“不反光“到“物理级真实“怎么选
开发语言·javascript·材质
ITmaster073119 分钟前
从零到一!前端搭建本地轻量化 RAG 问答系统
前端
夏炳辉.42 分钟前
Flex布局中 flex: 1 的完整解析与实战指南
前端·css·css3
CIO_Alliance1 小时前
AI提示系列(2)| Few-shot与ReAct有何不同? 大模型工具调用的底层逻辑详解
前端·人工智能·深度学习·神经网络·react.js·前端框架·ai+ipaas
waillyer1 小时前
企业知识库智能问答 Agent(React + Nest)
javascript·redis·agent
cindershade1 小时前
别只收三个数字:前端 RUM 如何建立可解释的体验数据链
前端
程序员-Benothing2 小时前
数据库的脏读、不可重复读和幻读:从面试标准答案到源码级原理
数据库·面试·职场和发展
前端 贾公子2 小时前
第09章:上下文与记忆 (4)
java·服务器·前端
Coodor2 小时前
使用web也可以写NFC微信小程序拉取
前端·微信小程序·小程序·nfc拉起小程序
数智启示录2 小时前
Flink CDC 机制精讲(四):一条 SQLServer CDC 事件如何保持顺序 【面试宝典】
数据库·面试·sqlserver·flink