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

  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布局
相关推荐
广白1 分钟前
钉钉小程序直传文件到 阿里云OSS
前端·vue.js·uni-app
沐怡旸3 分钟前
【底层机制】Android图形渲染体系深度解析:VSync信号机制
android·面试
TF男孩20 分钟前
写代码不怕Bug,就怕合同里有“竞业陷阱”
面试
沐怡旸42 分钟前
【穿越Effective C++】23.宁以non-member、non-friend替换member函数
c++·面试
zyfts44 分钟前
🔥告别 20 分钟等待!NestJS 生产级消息队列 BullMQ 实践指南
前端·后端
GISer_Jing1 小时前
3DThreeJS渲染核心架构深度解析
javascript·3d·架构·webgl
狗头大军之江苏分军1 小时前
【压力】一位一线炼钢工人的消失
前端·后端
拉不动的猪1 小时前
文件下载:后端配置、前端方式与进度监控
前端·javascript·浏览器
Amy_yang1 小时前
前端实现 Server-Sent Events 全解析:从代码到调试的实战指南
前端·uni-app
sean聊前端1 小时前
听说vite要一统江湖了,我看看怎么个事
前端