zoukankan      html  css  js  c++  java
  • 元素垂直居中的常见方法

        
      <--HTML-->
      <div class="box box1"> <div>flex</div> </div> <div class="box box2"> <div>inline-block</div> </div> <div class="box box3"> <div>position</div> </div> <div class="box box4"> <div class="cell"> <div>table</div> </div> </div> <div class="box box5"> <div>position+0</div> </div>

    公共样式:

    .box {
      width: 500px;
      height: 100px;
      background: lightblue;
      margin-bottom: 10px;
    }
    .box > div {
      width: 100px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background: pink;
    }

    1.display:flex: 

    .box1 {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    2.将元素设置为内联块再设置父元素的行高:

    .box2 {
      line-height: 100px;
      text-align: center;
    }
    .box2 > div {
      display: inline-block;
    }

    3.使用position定位:

    .box3 {
      position: relative;
    }
    .box3 > div {
      position: absolute;
      top: calc(50% - 25px);
      left: calc(50% - 50px);
    }

    4.给元素添加一个包裹层将元素设置为inline-block,包裹层设置为table-cell

    .box4 {
      display: table;
      vertical-align: middle;
    }
    .box4 .cell {
      display: table-cell;
      background: lightblue;
      vertical-align: middle;
      text-align: center;
    }
    .box4 .cell > div {
      display: inline-block;
      background: pink;
      width: 100px;
      height: 50px;
    }

    5.还是使用position但是将top、left、right、bottom都设为0

    .box5 {
      position: relative;
    }
    .box5 > div {
      position: absolute;
      margin: auto;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }

    在这几种方法中,当元素宽高改变时:

    可以看出使用flex、table-cell、position+0这三种方法实现的结果依然是垂直居中,所以在元素宽高未知的情况下想要居中可以使用这三种方法。

  • 相关阅读:
    旧贴-在 win7 / win8 下安装苹果系统 (懒人版)
    解决ios13摇一摇不能触发
    html+css面试合集
    Windows 2012 Server R2 添加用户
    Windows10专业版身份验证错误,可能由于CredSSP加密数据库修正
    STM32F4 7.STM32F4 独立看门狗
    STM32F4 6.STM32F4 外部中断
    STM32F4 5.STM32F4串口通讯
    STM32F4 4.STM32F4时钟系统
    STM32F4 3.GPIO按键输入,实现开关灯
  • 原文地址:https://www.cnblogs.com/cjw-ryh/p/7747387.html
Copyright © 2011-2022 走看看