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

  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布局
相关推荐
程序员林北北18 分钟前
【前端进阶之旅】节流与防抖:前端性能优化的“安全带”与“稳定器”
前端·javascript·vue.js·react.js·typescript
寻星探路1 小时前
【前端基础】HTML + CSS + JavaScript 快速入门(三):JS 与 jQuery 实战
java·前端·javascript·css·c++·ai·html
未来之窗软件服务2 小时前
未来之窗昭和仙君(六十九)前端收银台行为异常检测—东方仙盟练气
前端·仙盟创梦ide·东方仙盟·昭和仙君
大叔编程奋斗记2 小时前
两个日期间的相隔年月计算
前端·salesforce
2501_901147833 小时前
有序数组单一元素查找:从通用解法到算法极致优化——兼谈高性能计算基础思路
算法·面试·职场和发展
上海合宙LuatOS3 小时前
LuatOS核心库API——【io】 io操作(扩展)
java·服务器·前端·网络·单片机·嵌入式硬件·物联网
ShineWinsu3 小时前
对于C++:模版进阶的解析
开发语言·c++·面试·笔试·求职·进阶·模版
蘋天纬地3 小时前
给我简述下线程间通信方式
面试
GISer_Jing4 小时前
Taro多端开发
前端·react.js·taro
UrbanJazzerati4 小时前
一文介绍PostgreSQL与基本架构
后端·面试