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

  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布局
相关推荐
哆啦A梦158812 小时前
商城后台管理系统 04 登录-功能实现-数据持久化-vuex
javascript·vue.js·elementui
xinyu_Jina13 小时前
PaperStudio:WYSIWYG文档的Web实现——从CSS Print到客户端PDF生成的技术解析
前端·css·pdf
默默学前端13 小时前
html列表标签及css列表属性
前端·css·html5
老前端的功夫21 小时前
Vue 3 性能深度解析:从架构革新到运行时的全面优化
javascript·vue.js·架构
天天扭码1 天前
如何实现流式输出?一篇文章手把手教你!
前端·aigc·ai编程
前端 贾公子1 天前
vue移动端适配方案 === postcss-px-to-viewport
前端·javascript·html
GISer_Jing1 天前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
GSDjisidi1 天前
东京IT软件会社-(株)GSD|多种技术栈募集,高度人才+20分
开发语言·面试·职场和发展
明远湖之鱼1 天前
一种基于 Service Worker 的渐进式渲染方案的基本原理
前端