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

  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布局
相关推荐
JackSparrow41411 分钟前
前端安全之JS混淆+请求加密+请求签名以提升爬虫难度
前端·javascript·后端·爬虫·python·安全
IMPYLH19 分钟前
HTML 的 <em> 元素
java·前端·html
名为沙丁鱼的猫7292 小时前
【审计日志组件实践复盘】前端工程化 + 后端DDD架构(AOP切面拦截日志) + MBG
前端·架构
xqqxqxxq3 小时前
AI智能旅游规划系统 - 前端技术笔记
前端·笔记·旅游
陈随易9 小时前
bm2,MoonBit实现的pm2替代品
前端·后端·程序员
a11177611 小时前
农业数字孪生大屏网页 html开源
前端·html
圣光SG12 小时前
web操作题练习(六)
前端
闪亮的路灯13 小时前
威联通QTS使用自带web服务期代理前端(类似nginx)
前端·nginx·威联通
GitLqr13 小时前
深入理解 Flutter 架构:从 Widget 到 GPU 像素的全链路解析
flutter·面试·dart
kyriewen13 小时前
我用AI写了半年代码——回头看,这5个能力正在退化
前端·javascript·ai编程