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

  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布局
相关推荐
智航GIS21 分钟前
6.2 while循环
java·前端·python
2201_7578308721 分钟前
AOP核心概念
java·前端·数据库
雪人.24 分钟前
JavaWeb经典面试题
java·服务器·前端·java面试题
JIngJaneIL33 分钟前
基于java+ vue学生成绩管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端
a程序小傲35 分钟前
得物Java面试被问:反射机制的原理和应用场景
java·python·面试
小恒恒35 分钟前
2025 Vibe Coding 有感
前端·uni-app·trae
用户214118326360236 分钟前
dify案例分享-免费体验Dify + Qwen-Image-2512 文生图图生图全流程
前端
千寻girling44 分钟前
面试官 : “ 说一下 localhost 和127.0.0.1 的区别 ? ”
前端·javascript·面试
老华带你飞1 小时前
智能菜谱推荐|基于java + vue智能菜谱推荐系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
指尖跳动的光1 小时前
cookie可以实现不同域共享吗
前端