使一个不定宽高的盒子实现垂直水平居中(简单)

本文详细介绍了四种使用CSS实现元素垂直水平居中的方法,包括利用display:table-cell、CSS3 transform、Flexbox以及绝对定位结合margin:auto的技巧,适合前端开发者学习。

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

如何使一个不定宽高的元素实现垂直水平居中

结构

<div class="father">
    <div class="son"></div>
</div>
1.使用css方法:

父盒子设置:display:tbale-cell; text-align:center; vertical-align:middle;

子元素设置:dislplay: inline-block; vertical-align:middle;

.father  {
      display:tbale-cell; 
      text-align:center;
      vertical-align:middle;
       background-color: antiquewhite;
}
.son {
      dislplay: inline-block;  
      vertical-align:middle;
      background-color: bisque;
}
  • 属性:display:tbale-cell;
    • 1.使元素表现出类似td的效果,可以使不固定大小的元素出现垂直居中的效果
    • 2.不要与 float:left; position:absolute;一起使用
    • 3.magin设置无效,可以响应padding设置
    • 4.该属性对宽度和高度比较敏感
    • 5.不要对display:tbale-cell使用百分比设置宽度和高度
2.使用css3的 transform:

父盒子设置:dispaly: relative;

子盒子设置:transform: translate(-50%,-50%); position: absolute; top:50%; left:50%;

.father {
    dispaly: relative;
    background-color: antiquewhite;
}
.son {
   position: absolute; 
   top:50%;
   left:50%;
   transform: translate(-50%,-50%);  
   background-color: bisque;
}
3.让父盒子为flex容器:
 .father {
      width: 200px;
      height: 100px;
      background-color: antiquewhite;
      /* 设置父项 */
      display: flex;
      /* 设置子元素在主轴上的排列方式 */
      justify-content: center;
      /* 设置子元素在侧轴的排列方式(单行排列方式) */
      align-items: center;
    }
 .son {
     width: 100px;
     height: 40px;
     background-color: bisque;
    }
4.实现绝对定位元素的水平方向居中:margin: auto;
.father {
      width: 300px;
      height: 100px;
      background-color: aquamarine;
      position: relative;
    }

.son {
      width: 46px;
      height: 40px;
      background-color: bisque;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
    }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值