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

  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布局
相关推荐
0wioiw01 分钟前
Flutter基础(前端教程④-组件拼接)
前端·flutter
花生侠26 分钟前
记录:前端项目使用pnpm+husky(v9)+commitlint,提交代码格式化校验
前端
猿榜27 分钟前
魔改编译-永久解决selenium痕迹(二)
javascript·python
阿幸软件杂货间31 分钟前
阿幸课堂随机点名
android·开发语言·javascript
一涯33 分钟前
Cursor操作面板改为垂直
前端
我要让全世界知道我很低调40 分钟前
记一次 Vite 下的白屏优化
前端·css
threelab40 分钟前
three案例 Three.js波纹效果演示
开发语言·javascript·ecmascript
1undefined242 分钟前
element中的Table改造成虚拟列表,并封装成hooks
前端·javascript·vue.js
蓝倾1 小时前
淘宝批量获取商品SKU实战案例
前端·后端·api