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

  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布局
相关推荐
全栈老石13 分钟前
从硬编码到 Schema 推断:前端表单开发的工程化转型
前端·vue.js·架构
weixin_4624462315 分钟前
【原创实践】使用 shell 脚本批量创建 Linux 用户并生成随机密码
linux·服务器·前端
hid7117136632 分钟前
STM32F0 打造高性能无感 FOC 无刷电机控制方案,挑战 VESC 成本极限
css
软件技术NINI39 分钟前
娃娃店html+css 4页
前端·css·html
wordbaby1 小时前
TanStack Router 路径参数(Path Params)速查表
前端
梵尔纳多1 小时前
Electron 主进程和渲染进程通信
javascript·arcgis·electron
盟接之桥1 小时前
盟接之桥--说制造:从“找缝隙”到“一万米深”——庖丁解牛式的制造业精进之道
大数据·前端·数据库·人工智能·物联网·制造
巴拉巴拉~~2 小时前
Flutter 通用滑块组件 CommonSliderWidget:单值 / 范围 + 刻度 + 标签 + 样式自定义
开发语言·前端·javascript
韭菜炒大葱2 小时前
现代前端开发工程化:Vue3 + Vite 带你从 0 到 1 搭建 Vue3 项目🚀
前端·vue.js·vite
有意义2 小时前
从 useState 到 useEffect:React Hooks 核心机制详解
javascript·react.js·前端工程化