CSS水平垂直居中

本文介绍了在Web开发中常见的几种元素水平垂直居中的解决方案,包括flex布局的使用、相对绝对定位配合transform、伪元素以及flex+margin的技巧,总结了flex布局和相对定位是最常用的方法。
摘要由CSDN通过智能技术生成

1.为什么要水平垂直居中

        在日常开发过程中,我们往往在展示导航栏,列表项等需求时,往往涉及到最多的就是元素水平垂直居中,那么在开发中我们到底怎么样才能水平追至居中呢?下面这几种方法是比较常用和常见的。

2.flex的水平垂直居中

        我们可以给父盒子中使用flex布局,并且使用flex中的水平方向和竖直方向进行center,来保证我们的元素是水平垂直居中的

        

  .fatherBox1 {

    margin: 8px;

    width: 360px;

    height: 360px;

    display: flex;

    align-items: center;

    justify-content: center;

    background-color: red;

  }

  .childrenBox1 {

    background-color: blue;

  }

3.相对绝对布局 

        我们可以给父盒子相对定位,子盒子绝对定位,并且使用transform来辅佐进行布局,完成水平垂直居中的方案。

  .fatherBox2 {

    margin: 8px;

    width: 360px;

    height: 360px;

    position: relative;

    background-color: red;

  }

  .childrenBox2 {

    position: absolute;

    left: 50%;

    top: 50%;

    transform: translate(-50%, -50%);

    background-color: blue;

  }

4.相对绝对布局的另一种方案

  .fatherBox4 {

    position: relative;

    ;

    margin: 8px;

    width: 360px;

    height: 360px;

    background-color: red;

  }

  .childrenBox4 {

    position: absolute;

    width: 36px;

    height: 36px;

    left: 0;

    top: 0;

    right: 0;

    bottom: 0;

    margin: auto;

    background-color: blue;

  }

5.伪元素

        伪元素这种会有局限性,只限制子盒子为块级元素。

 

  .box {

    width: 200px;

    height: 200px;

    border: 1px solid;

    text-align: center;

  }

  .box::before {

    content: "";

    line-height: 200px;

  }

  .child {

    display: inline-block;

    background: red;

  }

6.flex+margin 

        下面这种方式会在另一篇文章中详细说明,为什么子盒子使用margin auto就可以完成水平垂直居中了。

  .fatherBox3 {

    display: flex;

    margin: 8px;

    width: 360px;

    height: 360px;

    background-color: red;

  }

  .childrenBox3 {

    width: 36px;

    height: 36px;

    margin: auto;

    background-color: blue;

  }

7.总结

        其实上面这些用法我们在开发中用的最多的就是flex布局和相对绝对定位这两种方法。 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值