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

  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布局
相关推荐
换日线°13 分钟前
前端炫酷展开效果
前端·javascript·vue
夏幻灵1 小时前
过来人的经验-前端学习路线
前端
CappuccinoRose1 小时前
React框架学习文档(七)
开发语言·前端·javascript·react.js·前端框架·reactjs·react router
FFF-X1 小时前
前端字符串模糊匹配实现:精准匹配 + Levenshtein 编辑距离兜底
前端
Hi_kenyon2 小时前
Ref和Reactive都是什么时候使用?
前端·javascript·vue.js
小小测试开发2 小时前
UI自动化测试:CSS定位方式超详细解析(附实战示例)
css·ui·tensorflow
無森~2 小时前
HBase优化面试题
java·面试·hbase
止观止2 小时前
深入理解 interface vs type:终结之争
前端·typescript
css趣多多2 小时前
vue环境变量
前端
RFCEO2 小时前
前端编程 课程十五、:CSS核心基础3:文字+段落样式
前端·css·文字+段落样式·css文本样式·美化页面文本内容·演示动画说明·单行文字垂直居中技