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

  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布局
相关推荐
两点王爷1 小时前
Java 面试高频:JWT、Cookie、Session、Token 鉴权详解
java·开发语言·面试
ShineWinsu2 小时前
对于Qt:条件变量(QWaitCondition)的解析
c++·qt·面试·线程·条件变量·客户端·锁
Java展博2 小时前
[前端够用就好] 跨域报错时,浏览器到底在拦谁
前端·状态模式
用户112936112193 小时前
npm 都提示成功了,node_modules 为什么还占着 370M?
linux·前端·后端
掘金安东尼4 小时前
Agent Harness 也有 benchmark:评分榜与评测工作台现状
前端·agent
digger_4194 小时前
从零理解 Electron:主进程、渲染进程、preload 与 IPC 实战
前端·electron
nice_lcj5204 小时前
依赖注入的三种方式:构造器、Setter、字段怎么选
java·spring·面试·依赖注入·字段注入·构造器注入
去伪存真5 小时前
别让你的 RAG 平台“花五份钱、答一份结巴的题”:幂等性架构的自我修养
前端·agent
snow@li6 小时前
前端:导入EXCEL并解析文件内容,demo
前端·javascript·vue.js
补码缩写6 小时前
压缩PNG不损失透明:只量化RGB、alpha原样留的减色流程
前端