CSS元素的水平垂直居中(超级全)面试必背

16 篇文章 0 订阅
14 篇文章 0 订阅

一.已知宽高

1. 子元素+vertical-align,display: inline-block 父元素+line-height,text-align
 .a1 {
      width: 800px;
      height: 800px;
      background: orange;
      text-align: center;
      line-height: 800px;
    }
 .a2 {
      width: 300px;
      height: 300px;
      background: blue;
      vertical-align: middle;
      display: inline-block;
    } 
2.用定位position, margin: auto; 父元素给relative 子元素给absolute
 .a1 {
      width: 800px;
      height: 800px;
      background: orange;
      position: relative;
    }
 .a2 {
      width: 300px;
      height: 300px;
      background: blue;
      position: absolute;
      margin: auto;
      left: 0;
      bottom: 0;
      right: 0;
      top: 0;
    } 
3.positon+calc函数
.a1 {
      width: 800px;
      height: 800px;
      background: orange;
      position: relative;
    }
.a2 {
      width: 300px;
      height: 300px;
      background: blue;
      position: absolute;
      top: calc(50% - 300px / 2);
      left: calc(50% - 300px / 2);
    }
4. position+margin-top+margin-left
  .a1 {
      width: 800px;
      height: 800px;
      background: orange;
      position: relative;
    } 
  .a2 {
      width: 300px;
      height: 300px;
      background: blue;
      position: absolute;
      top: 50%;
      margin-top: -150px;
      left: 50%;
      margin-left: -150px;
    } 

二.宽高未知

1.position+translate
    .a1 {
      width: 600px;
      height: 600px;
      background: orange;
      position: relative;
    }
    .a2 {
      width: 100px;
      height: 100px;
      background-color: blue;
      position: absolute;
      transform: translate(-50%, -50%);
      top: 50%;
      left: 50%;
    } 
2. 弹性盒flex
    .a1 {
      width: 600px;
      height: 600px;
      background: orange;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .a2 {
      width: 100px;
      height: 100px;
      background-color: blue;
    } 
3.弹性盒flex-box 子元素margin:auto;
    .a1 {
      width: 600px;
      height: 600px;
      background: orange;
      display: flex;
    }
    .a2 {
      width: 100px;
      height: 100px;
      background-color: blue;
      margin: auto;
    } 
4.table-cell
    .a1 {
      width: 600px;
      height: 600px;
      background: orange;
      display: table-cell;
      vertical-align: middle;
      text-align: center;
    }
    .a2 {
      width: 100px;
      height: 100px;
      background-color: blue;
      display: inline-block;
    } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值