css水平垂直居中的几种方法

水平居中

1.通过margin:0 auto

给需要居中的容器直接设置margin:0 auto;

css代码:

    .father{
      width: 300px;
      height: 300px;
      background-color: bisque;
      
    }
    .son{
      width: 100px;
      height: 100px;
      background-color: cadetblue;
      margin: 0 auto;
    }

 2.子绝父相

给需要居中的容器设置绝对定位,对其父容器设置相对定位,然后对居中容器添加left:50%,并使用margin-left:-居中容器宽度的一半;

    .father{
      width: 300px;
      height: 300px;
      background-color: bisque;
      position: relative;
    }
    .son{
      width: 100px;
      height: 100px;
      background-color: cadetblue;
      position: absolute;
      left: 50%;
      margin-left: -50px;
    }

 3.flex布局

在父容器中开启flex布局,再添加justify-content:center

    .father{
      width: 300px;
      height: 300px;
      background-color: bisque;
      display: flex;
      justify-content: center;
    }
    .son{
      width: 100px;
      height: 100px;
      background-color: cadetblue;
    }

 

2.垂直居中

 

1.子绝父相

方法跟水平居中类似,只是将水平方向改为垂直方向,所以需要将left改为top。

    .father{
      width: 300px;
      height: 300px;
      background-color: bisque;
      position: relative;
      
    }
    .son{
      width: 100px;
      height: 100px;
      background-color: cadetblue;
      position: absolute;
      top: 50%;
      margin-top: -50px;
    }

也可以结合margin使用,把要垂直居中的元素相对于父元素绝对定位,top和bottom设置为相等的值,再设置margin:auto 0;

    .father{
      width: 300px;
      height: 300px;
      background-color: bisque;
      position: relative;
      
    }
    .son{
      width: 100px;
      height: 100px;
      background-color: cadetblue;
      position: absolute;
      top: 0;
      bottom: 0;
      margin: auto 0;
    }

 2.flex布局

在父容器中开启flex布局,再添加align-items: center;

    .father{
      width: 300px;
      height: 300px;
      background-color: bisque;
      display: flex;
      align-items: center;
      
    }
    .son{
      width: 100px;
      height: 100px;
      background-color: cadetblue;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值