CSS 垂直水平居中总结(全)

目录

以下面的代码为例

html 复制代码
<div class="container">
  <div class="item"></div>
</div>

1,不需要知道元素的宽高

1.1,flex(2种)

最常用的,没有任何限制。

css 复制代码
.container{
  display: flex;
  justify-content: center;
  align-items: center;
}

css 复制代码
.container{
  display: flex;
}
.item {
  margin: auto;
}

1.2,grid(2种)

css 复制代码
.container {
  display: grid;
  align-content: center;
  justify-content: center;
}
css 复制代码
.container{
  display: grid;
}
.item {
  margin: auto;
}

1.3,verticle-align:middle

限制:

  1. 元素 display: inline-block
  2. 需要有一个兄弟元素作为参照物,并且会以最高的兄弟元素为作为参考,垂直于兄弟元素的中心点。所以可以利用伪元素。
css 复制代码
.container {
  text-align: center;
}
.container::before {
  content : '';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}
.item {
  display: inline-block;
  width: 100px;
  height: 100px;
  vertical-align: middle;
}

1.4,绝对定位

css 复制代码
.container {
   position: relative;
}
.item {
   width: 100px;
   height: 100px;
   position: absolute;
   left: 0;
   top: 0;
   bottom: 0;
   right: 0;
   margin: auto;
}

上下左右为 0 可以替换为 inset: 0,不过注意可能会有兼容性问题,参考

1.5,table-cell

限制:元素 display: inline-block

css 复制代码
.container {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.item {
  display: inline-block;
  width: 100px;
  height: 100px;
}

2,需要知道元素的宽高

2.1,绝对定位

css 复制代码
.container {
   position: relative;
}
.item {
   width: 100px;
   height: 100px;
   position: absolute;
   left: 50%;
   top: 50%;
   margin: -50px 0 0 -50px;
   /* 或 */
   transform: translateX(-50px) translateY(-50px);
}

阮一峰-网格布局

以上。

相关推荐
李剑一4 分钟前
uni-app实现网络离线定位
前端·trae
鲨莎分不晴5 分钟前
Nginx 部署前端项目实战指南
运维·前端·nginx
码界奇点14 分钟前
基于Vue3与TypeScript的后台管理系统设计与实现
前端·javascript·typescript·vue·毕业设计·源代码管理
ashcn200120 分钟前
水滴按钮解析
前端·javascript·css
攀登的牵牛花20 分钟前
前端向架构突围系列 - 框架设计(五):契约继承原则
前端·架构
豆苗学前端1 小时前
你所不知道的前端知识,html篇(更新中)
前端·javascript·面试
一 乐1 小时前
绿色农产品销售|基于springboot + vue绿色农产品销售系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端·宠物
zzjyr1 小时前
Webpack 生命周期原理深度解析
前端
xiaohe06011 小时前
💘 霸道女总裁爱上前端开发的我
前端·游戏开发·trae
sophie旭1 小时前
内存泄露排查之我的微感受
前端·javascript·性能优化