CSS 让容器水平垂直居中的方法

本文总结了四种常用CSS方法实现容器的水平垂直居中:1) 使用flex布局;2) 通过position定位;3) 利用table-cell和vertical-align中间对齐;4) 利用grid栅格布局。这些方法在实际工作中和面试中都常被考察。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工作中常用的使容器垂直、水平居中的方法,也是面试中常考的问题,在此归结为4类:

<!-- 公用html代码 -->
<div class="parent">
    <div class="child"></div>
</div>
方案一:使用flex布局
.parent{ 
  width:3rem;  
  height:5rem;
  background: #eee;
  display: flex; // 弹性盒子
  justify-content: center; // 水平方向居中显示
  align-items: center; // 垂直方向居中显示
}
.child{
  width:2rem;
  height:2rem;
  background:pink;
}
方案二:使用posiiton定位
.parent{ 
  width:3rem;  
  height:5rem;
  background: #eee;
  position:relative; // 父容器相对定位
}
.child{
  width:2rem;
  height:2rem;
  background:pink;   
  position:absolute; // 子容器绝对定位
  top: 50%;
  left: 50%;
  margin-top: -1rem;
  margin-left: -1rem; // 知道容器宽、高情况下
  // transform: translate(-50%, -50%); // 不知道宽、高情况下
}
方案三:使用table-cell + vertical-align: middle
.parent{
  width:3rem;  
  height:5rem;
  background: #eee;
  display: table-cell;
  vertical-align: middle; // 父容器设置元素居中对齐
  text-align: center; 
}
.child{
  display: inline-block; // 这里必须设置为行内块元素显示,vertical-align对块元素不生效
  width:2rem;
  height:2rem;
  background:pink; 
  vertical-align: middle; // 子容器设置居中对齐
}
方案四:使用grid栅格
.parent{ 
  width:3rem;  
  height:5rem;
  background: #eee;
  display: grid; // 如容器设置栅格
}
.child{
  width:2rem;
  height:2rem;
  background:pink;  
  margin: auto; // 子容器设置margin
}

以上方案展示效果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值