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);
}

阮一峰-网格布局

以上。

相关推荐
codezzzsleep9 分钟前
让个人智能体安全地接触外部资料
java·前端·安全
掘金安东尼29 分钟前
文档不一致,会伤害 AI 编码智能体吗?智能体
前端
xurileidian8 小时前
第 24 篇 · 边玩边学Python · while 与死循环怎么退
服务器·前端·python
Highcharts.js10 小时前
Highcharts软件绘制图表:用数据构建可视化图形
前端·学习·信息可视化·数据分析·js·开发实战·highcharts
Hilaku11 小时前
2027 制药行业 ERP 系统架构选型笔记:从 GMP 合规追溯到动态 MCP 接入
前端·javascript·程序员
掘金安东尼13 小时前
人工智能AI
前端
kyriewen13 小时前
AI 面试官筛前端简历,先出局的不是写代码慢的
前端·面试·程序员
BigTopOne13 小时前
10 引用与借用:& 和 &mut
前端
粥里有勺糖13 小时前
视野修炼-技术周刊第139期 | AI 不会让时间变多
前端·github·ai编程
打呵欠的猫15 小时前
我用 AI 把 CSS 从"每人一种风格"统一成了设计系统 Token,再也不吵"用什么颜色"了
css·ai编程