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

  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布局
相关推荐
muyouking115 小时前
WASM 3.0 两大领域实战:SvelteKit前端新范式(完整版)
前端·wasm
Hilaku5 小时前
当你的Ant-Design成了你最大的技术债
前端·javascript·前端框架
Highcharts.js5 小时前
时间序列图的“性能陷阱”:Highcharts “金融级”优化方案
前端·python·金融
摇滚侠6 小时前
Vue 项目实战《尚医通》,完成预约通知业务,笔记21
前端·vue.js·笔记·前端框架
IT_陈寒6 小时前
SpringBoot性能优化实战:我从10万QPS项目中总结的7个核心技巧
前端·人工智能·后端
顾安r6 小时前
11.9 脚本网页 消消乐
前端·javascript·flask·html·pygame
宋哈哈6 小时前
页面水印sdk源码
java·前端·javascript
Kikyo--7 小时前
前端基础面试题(Css,Html,Js,Ts)
前端·javascript·css·typescript·html
火车叼位7 小时前
处理volta切换node版本之后pnpm没有识别的问题
前端·javascript
七号练习生.c7 小时前
JQuery&Ajax
前端·ajax·jquery