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

  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布局
相关推荐
Jinuss11 分钟前
源码分析之React中ReactDOMRoot实现
前端·javascript·react.js
摘星编程15 分钟前
React Native鸿蒙版:React Query无限滚动
javascript·react native·react.js
web守墓人20 分钟前
【前端】vue3的指令
前端
想起你的日子1 小时前
EFCore之Code First
前端·.netcore
框架图1 小时前
Html语法
前端·html
深耕AI1 小时前
【wordpress系列教程】07 网站迁移与备份
运维·服务器·前端·数据库
月空MoonSky2 小时前
解决使用Notepad++出现异型字或者繁体字体问题
java·javascript·notepad++
joan_852 小时前
input禁止自动填充
前端·elementui·vue
研☆香2 小时前
简单的复选框 全选 反选功能
javascript