总结六种盒子居中的方法

107 阅读1分钟

实现盒子 水平垂直居中 的思路只有两种

利用标签自带的效果实现居中 / 通过调整父子盒子之间的位置关系实现居中

效果图:

image.png

1. 定位 + transform

<style>
    #father{
      position: relative;
    }
    #son{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
</style>

2. 定位 + margin:auto

<style>
    #father{
      position: relative;
    }
    #son{
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
    }
</style>

3. 定位 + margin负间距

<style>
    #father{
      position: relative;
    }
    #son{
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -100px;
      margin-top: -100px;
      /* 100px为子盒子宽高的一半 */
    }
</style>

4. flex布局

<style>
    #father{
      display: flex;
      justify-content: center;
      align-items: center;
    }
    #son{
      /* 子盒子不需要调样式 */
    }
</style>

5. display: table-cell

<style>
    #father{
      /* 把div变成表格中的单元格元素 */
      display: table-cell;
      /* 单元格中文字对齐方式改为垂直居中对齐 */
      vertical-align: middle
    }
    #son{
      /* 水平居中 */
      margin: 0 auto;
    }
</style>

6. 利用button标签

<style>
    #father{
      /* button标签默认内容垂直居中 */
    }
    #son{
      /* 水平居中 */
      margin: 0 auto;
    }
</style>
<html>
  <body>
    <button id="father">
      <div id="son"></div>
    </button>
  </body>
</html>