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

  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布局
相关推荐
s91236010120 分钟前
【Rust】使用lldb 调试core dump
前端·javascript·rust
沐怡旸21 分钟前
【穿越Effective C++】条款21:必须返回对象时,别妄想返回其reference——对象返回的语义与效率平衡
c++·面试
前端开发呀43 分钟前
🔥 99%由 Trae AI 开发的 React KeepAlive 组件,竟然如此优雅!✨
前端·trae
不是鱼1 小时前
Canvas学习笔记(一)
前端·javascript·canvas
我有一棵树1 小时前
React 中 useRef 和 useState 的使用场景区别
前端·javascript·react.js
喵个咪1 小时前
Qt6 QML 实现DateTimePicker组件
前端·qt
yinuo1 小时前
CSS奇技淫巧:用你意想不到的4种属性实现裁剪遮罩效果
前端
晓翔仔1 小时前
网络安全之Web入侵场景
前端·安全·web安全·网络安全·信息安全
一叶飘零_sweeeet1 小时前
2025 年 Redis 面试天花板
redis·缓存·面试
想努力找到前端实习的呆呆鸟1 小时前
Uniapp如何下载图片到本地相册
前端·vue.js·微信小程序