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

  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布局
相关推荐
吃饺子不吃馅10 分钟前
如何设计一个 Canvas 事件系统?
前端·canvas·图形学
theOtherSky16 分钟前
element+vue3 table上下左右键切换input和select
javascript·vue.js·elementui·1024程序员节
Baklib梅梅25 分钟前
无头内容管理系统:打造灵活高效的多渠道内容架构
前端·ruby on rails·前端框架·ruby
会联营的陆逊38 分钟前
JavaScript 如何优雅的实现一个时间处理插件
javascript
over6971 小时前
浏览器里的AI魔法:用JavaScript玩转自然语言处理
前端·javascript
Amy_cx1 小时前
搭建React Native开发环境
javascript·react native·react.js
over6971 小时前
弹性布局完全指南:从文档流到Flexbox实战
css
代码AI弗森1 小时前
Python × NumPy」 vs 「JavaScript × TensorFlow.js」生态全景图
javascript·python·numpy
疏狂难除1 小时前
关于spiderdemo第二题的奇思妙想
javascript·爬虫
渣渣盟1 小时前
探索Word2Vec:从文本向量化到中文语料处理
前端·javascript·python·文本向量化