小盒子怎么在大盒子中水平并且垂直居中的4种方法

小盒子怎么在大盒子中水平并且垂直居中的4种方法!

1. 方法一

  • 父元素相对定位,子元素绝对定位,绝对定位中上下左右都为0,再加上margin:auto
   .father {
      position: relative;
      width: 500px;
      height: 500px;
      margin: 100px auto;
      background-color: pink;
    }

    .son {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      width: 300px;
      height: 300px;
      background-color: red;
    }

2. 方法二

  • 子绝父相在加上transform(说明:transform是css3新属性,属于动画系列,里面translate是平移的意思,里面设置两个值是相对于自身元素大小来移动的!正值是向下和向右移动,负值则往相反方向移动)
  .father {
      position: relative;
      width: 500px;
      height: 500px;
      margin: 100px auto;
      background-color: pink;
    }

    .son {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 300px;
      height: 300px;
      background-color: red;
    }

3. 方法三:

  • 这个方法相当于把块级元素转换为行内块元素来设置,具体设置方法我在代码中注释了出来;
  .father {
      /* 使元素呈单元格的样式显示 */
      display: table-cell;
      /* 水平局中 */
      text-align: center;
      /* 垂直居中 */
      vertical-align: middle;
    }

    .son {
      /* 把子盒子设置为行内块元素 */
      display: inline-block;
    }

4. 方法四

  • 利用弹性盒子来设置,(前面有发布关于弹性盒子模型的学习),不用设置子元素
    .father {
      /* 将盒子模型转换为弹性盒子模型 */
      display: flex;
      /* 设置元素在主轴方向的水平居中 */
      justify-content: center;
      /* 设置元素在侧轴(垂直)方向的垂直居中 */
      align-items: center;
      width: 500px;
      height: 500px;
      margin: 100px auto;
      background-color: pink;
    }
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值