当父级标签没有给定高度时,那么只需要给定 padding:10px 0; 就能将子标签垂直居中
当若是父级标签给定了高度,我们就需要通过其它方式来实现子标签的垂直居中:

1、使用 table 自带功能

使用 table 标签,并给定高度,其子元素会自动实现垂直居中

<style>
  .parent{
    border: 1px solid red;
    height: 600px;
  }
  .child{
    border: 1px solid green;
  }
</style>
<table class="parent">
  <tr>
    <td class="child">hihihi</td>
  </tr>
</table>
2、将 div 装成 table

将父标签的 display 设置为 table,再设置子标签垂直居中: vertical-align: middle;

<body>
  <style>
    .table{
      display: table;
      border: 1px solid red;
      height: 600px;
    }

    .td{
      display: table-cell;
      border: 1px solid blue;
      vertical-align: middle;
    }
  </style>
  <div class="table">
      <div class="td">
        <div class="child">hihihi</div>
    </div>
  </div>
</body>
3、夹心饼干法 - 饼干高度为 100% + inline block

给子标签的前后添加一个span标签,并将这两个span标签连同 child 设置为 inline-block,垂直对齐方式设置为居中(),span标签的高度为 100%,撑开高度。

<body>
  <style>
    .parent{
      height: 200px;
      text-align: center;
    }
    .child{
      display: inline-block;
      vertical-align: middle;
    }
    .parent .before,
    .parent .after{
      display: inline-block;
      height: 100%;
      vertical-align: middle;
    }
  </style>
  <div class="parent">
    <span class=before></span>  
    <div class="child">hihihihi</div>
    <span class=after></span>
  </div>
</body>
4、使用定位
4.1、绝对定位 + margin-top: 50%
<body>
  <style>
    .parent{
      height: 200px;
      position: relative;
    }
    .child{
      width: 300px;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -150px;
      height: 100px;
      margin-top: -50px;
    }
  </style>
  <div class="parent">
    <div class="child">hihihi</div>
  </div>
</body>
4.2、绝对定位 + margin: auto
<body>
  <style>
    .parent{
      height: 200px;
      position: relative;
    }
    .child{
      position: absolute;
      width: 100px;
      height: 100px;
      margin: auto;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
    }
  </style>
  <div class="parent">
    <div class="child">hihihi</div>
  </div>
</body>
4.3、绝对定位 + translate(-50%,-50%)
<body>
  <style>
    .parent{
      height: 200px;
      position: relative;
    }
    .child{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
  </style>
  <div class="parent">
    <div class="child">hihihi</div>
  </div>
</body>
5、使用flex布局

flex布局中: justify-content: center; 设置为垂直方向居中;align-items: center; 设置为水平方向居中

<body>
  <style>
    .parent{
      height: 200px;
      border: 3px solid red;
      display: flex;
      justify-content: center; /* 垂直方向居中 */
      align-items: center; /* 水平方向居中 */
    }
    .child{
      border: 3px solid green;
      text-align:center;
      width: 100px;
    }
  </style>
  <div class="parent">
    <div class="child">hihihi</div>
  </div>
</body>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐