盒子水平垂直居中

176 阅读2分钟

当我们在写前端页面布局时,经常会用到盒子的水平垂直居中属性,而我们这里所说的水平垂直居中是相当于一个参照物来排布的,也就是子盒子相对于父盒子水平垂直居中。

方法一:利用定位(常用方法,推荐)

这种方法就是父盒子使用相对定位,子盒子使用绝对定位,然后利用top: 50%,left:50%,来让子盒子相距父盒子上边界,左边界宽高的50%,利用margin-top,margin-left返回子盒子自身宽高的50%

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div class="fa">
      <div class="son"></div>
    </div>
  </body>
</html>
<style>
  .fa {
    width: 500px;
    height: 500px;
    background-color: blanchedalmond;
    /* 父盒子开启相对定位 */
    position: relative;
  }

  .son {
    width: 200px;
    height: 200px;
    background-color: aqua;
    /* 父盒子开启绝对定位 */
    position: absolute;

    top: 50%;
    /* 相当于父盒子上边界走父盒子高度的50% */
    left: 50%;
    /*相对于父盒子左边界走父盒子宽度的50%*/
    margin-top: -100px;
    /*向上走回自身高度的一半*/
    margin-left: -100px;
    /*向左走回自身宽度的一半*/
  }
</style>

方法二: 利用margin:auto;

有时要实现一些元素水平垂直都居中,但是这些元素未知大小,例如一些图片或未知大小的块元素,margin:auto会自动计算子元素和父元素之间的边距,并进行居中。

.fa {
    background-color: red;
    width: 300px;
    height: 300px;
    position: relative;
  }
  .son {
    background-color: #000;
    width: 100px;
    height: 100px;
    position: absolute;
    margin: auto;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }

方法三: 利用display:flex;

这种是利用flex布局设置主轴从轴居中

.fa {
    background-color: red;
    width: 300px;
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .son {
    background-color: #000;
    width: 100px;
    height: 100px;
  }

方法四:计算父盒子与子盒子的空间距离

要注意给父盒子添加边框,防止会产生外边距塌陷的问题

.fa {
    background-color: red;
    width: 300px;
    height: 300px;
        /* 父盒子添加边框,防止外边距塌陷 */
    border: 1px solid transparent;
  }
  .son {
    background-color: #000;
    width: 100px;
    height: 100px;
    margin-top: 100px;
    margin-left: 100px;
  }

方法五: 利用transform变换实现居中

与方法一类似,同样也是使用子绝父相,先让子盒子在父盒子的上和左50%再返回自身宽高的50%,这样就可以实现居中效果了

.fa {
    background-color: red;
    width: 300px;
    height: 300px;
    position: relative;
  }
  .son {
    background-color: #000;
    width: 100px;
    height: 100px;
    position: absolute;
    margin: auto;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }