在不知道父子元素的宽高时,怎么水平垂直居中

在面试时经常会问到css布局的问题,尤其是居中问题,于是把想到的方法做以下总结。如有补充,欢迎私聊哦~

一、块级元素

1、flex方法

HTML文件

  <body>
    <div class="father">
      <div class="child"></div>
    </div>
  </body>

 CSS文件

.father {
      background-color: yellow;
      width: 500px;      /*此处未知,方面展示所以假设了宽高*/
      height: 300px;     /*此处未知,方面展示所以假设了宽高*/
      display: flex;
      justify-content: center;  /*垂直居中*/
      align-items: center;      /*水平居中*/
    }
.child {
      width: 200px;      /*此处未知,方面展示所以假设了宽高*/
      height: 100px;     /*此处未知,方面展示所以假设了宽高*/
      background-color: thistle;
    }

2、使用css3 的translate+absolute

HTML文件

  <body>
    <div class="father">
      <div class="child"></div>
    </div>
  </body>

CSS文件

.father {
      background-color: yellow;
      width: 500px;
      height: 300px;
      position: relative;
    }
.child {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 200px;
      height: 100px;
      background-color: thistle;
    }

3、 使用absolute + margin

    .father {
        border: 10px solid red;
        height: 400px;
        position: relative;
    }

    .child {
        position: absolute;
        width: 200px;
        height: 200px;
        background-color: gray;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        margin: auto;

    }

二、行内元素

水平居中:

1.首先看它的父元素是不是块级元素,如果是,则直接给父元素设置 text-align: center; 

2.如果不是,则先将其父元素设置为块级元素,再给父元素设置 text-align: center;

垂直居中:

1.只需要设置行内元素的"行高line-height等于盒子的高"即可,仅适用于纯文字;

2.父元素设置成table-cell表格形式,使用vertical-align: middle即可使内联元素垂直居中;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值