【学习】CSS实现水平垂直居中的方式

本文详细介绍了使用CSS实现元素水平垂直居中的多种方法,包括absolute+负margin、marginauto、calc、transform、line-height、flex布局、grid布局、css-table等,对比了它们的优缺点及适用场景。

CSS实现水平垂直居中的方式

在这里插入图片描述

居中元素定宽高

一、absolute+负margin

1、父元素相对定位,子元素绝对定位
2、因为绝对定位的百分百是相对于父元素的宽高,但绝对定位是基于元素的左上角
3、借助外边距的负值,设置子元素的外边距为子元素宽度一般的负值
优点:好理解,兼容性也比较好
缺点:需要知道子元素的宽高

后面的代码示例均已这个例子进行改动

 <style>
    .wp{
      border:1px solid red;
      width: 300px;
      height: 300px;
      >position: relative;
    }
    .box{
      background-color: coral;
      >position: absolute;
      >top: 50%;
      >left: 50%;
      >margin-left: -50px;
      >margin-top: -50px;
    }
    .box.size{
      width: 100px;
      height: 100px;
    }
  </style>

 <div class="wp">
    <div class="box size">定宽高</div>
  </div>

二、absolute+margin auto

1、设置各个方向的距离都是0
2、将margin设为auto,就可以实现各个方向的居中
优点:兼容性挺好
缺点:需要知道子元素的宽高

代码只要改变子元素的样式

.box{
      background-color: coral;
      position: absolute;
      top: 0;
      left:0;
      right: 0;
      bottom: 0;
      margin: auto;
    }

三、absolute+calc

1、css3计算属性
2、top的百分比是基于元素的左上角,减去宽度的一半就好

缺点:需要知道子元素的宽高,兼容性依赖calc的兼容性

 .box{
      background-color: coral;
      position: absolute;
      top:calc(50%-50px);
      left:calc(50%-50px);
    }

居中元素不定宽高

一、absolute+transform

优点:不需要知道子元素的宽高,
缺点:兼容性依赖translate的兼容性

<div class="wp">
    <div class="box">定宽高</div>
  </div>
 .box{
      background-color: coral;
      position: absolute;
      top:50%;
      left:50%;
      transform: translate(-50%,-50%);
    }

二、line-height

1、利用行内元素居中属性
2、把盒子设置成行内元素
3、通过text-align做到水平居中
4、通过vertiacl-align做到垂直居中
优点:不需要知道子元素的宽高,
缺点:需要在子元素中将文字显示重置为想要的效果

 .wp{
      border:1px solid red;
      width: 300px;
      height: 300px;
      line-height: 300px;
      text-align: center;
      font-size: 0px;  
    }
    .box{
      background-color: coral;
      font-size: 16px;
      display: inline-block;
      vertical-align: middle;
      line-height: initial;
      text-align: left;  
      /* 修正文字 */
    }
   

三、flex布局

优雅的实现水平垂直居中

  .wp{
      border:1px solid red;
      width: 300px;
      height: 300px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

四、grid布局

优点:代码量少
缺点:兼容性不如flex

   .wp{
      border:1px solid red;
      width: 300px;
      height: 300px;
      display: grid;   
    }
    .box{
      background-color: coral;
      align-self: center;
      justify-self: center;
    }

五、css-table

 .wp{
      border:1px solid red;
      width: 300px;
      height: 300px;
      display:table-cell;   
      text-align: center;
      vertical-align: middle;
    }
    .box{
      background-color: coral;
     display: inline-block;
    }

在这里插入图片描述

总结

1、宽高固定,pc端有兼容性 absolute+负margin
2、宽高不固定, pc端有兼容性 css-table
3、pc端无兼容要求 flex布局
4、移动端 flex布局

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值