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这三种方法实现的结果依然是垂直居中,所以在元素宽高未知的情况下想要居中可以使用这三种方法。

  • 相关阅读:
    利用 pandas库读取excel表格数据
    Spark学习笔记3——RDD(下)
    Spark学习笔记2——RDD(上)
    Spark学习笔记1——第一个Spark程序:单词数统计
    Spark学习笔记0——简单了解和技术架构
    java标识符和关键字
    数据库事务ACID特性(原子性、一致性、隔离性、持久性)
    大数据系统的运行
    虚拟机和hadoop
    大数据基础1
  • 原文地址:https://www.cnblogs.com/cjw-ryh/p/7747387.html
Copyright © 2011-2022 走看看