盒子水平和垂直居中的方法

1.利用定位position和transform

    *{
      padding: 0;
      margin: 0;
    }
    html,body{
      width: 100%;
      height: 100%;
    }
    .father{
      height: 100%;
      width: 100%;
      background-color: red;
    }
    .son{
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      width: 200px;
      height: 200px;
      background-color: skyblue;
    }
html部分
  <div class="father">
    <div class="son">
    </div>
  </div>

在这里插入图片描述

2.或者利用margin-top 负的自身的一半

此时需要知道盒子的大小
利用相对定位使自身偏移父盒子大小的一般,然后利用margin-top或margin-left的负值将自身再平移回去。

    .father{
      height: 100%;
      width: 100%;
      background-color: red;
    }
    .son{
      position: absolute;
      left: 50%;
      top: 50%;
      margin-top: -100px
      width: 200px;
      height: 200px;
      background-color: skyblue;
    }

3.利用弹性盒子flex属性

通过对父盒子定义flex,使子元素为伸缩盒子,再利用
align-itema:center; 使得元素垂直居中
justify-conter:ceneter; 使得盒子中的元素水平居中

    *{
      padding: 0;
      margin: 0;
    }
    html,body{
      width: 100%;
      height: 100%;
    }
    .father{
      height: 100%;
      width: 100%;
      background-color: red;
      display: flex;
      align-items: center;  /*定义子元素垂直居中 */
      justify-content: center;  /*定义子元素水平居中 */
    }
    .son{
      width: 200px;
      height: 200px;
      background-color: skyblue;
    }

最后使用css书写顺序的规范

1.位置属性(position, top, right, z-index, display, float等)

2.大小(width, height, padding, margin)

3.文字系列(font, line-height, letter-spacing, color- text-align等)

4.背景(background, border等)

5.其他(animation, transition等)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值