如何使一个盒子水平居中的五种办法

69 阅读1分钟
<style>
  /* 方法一: 利用定位*/
  .father {
    width: 500px;
    height: 500px;
   background-color: yellow;
    position: relative;
  }
  .child {
    width: 200px;
    height: 200px;
   background-color: aqua;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
  }

  /* 方法二:利用margin:auto */
  .father {
    width: 500px;
    height: 500px;
    background-color: yellow;
    position: relative;
  }
  .child {
    width: 200px;
    height: 200px;
    background-color: aqua;
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  /* 方法三: 利用display:table-cell */
  .father {
    width: 500px;
    height: 500px;
    background-color: yellow;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
  }
  .child {
    width: 200px;
    height: 200px;
    background-color: aqua;
    display: inline-block;
  }

  /* 方法四:利用display:flex */
  .father {
    width: 500px;
    height: 500px;
    background-color: yellow;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .child {
    width: 200px;
    height: 200px;
    background-color: aqua;
  }

  /* 方法五:利用transform */
  .father {
    width: 500px;
    height: 500px;
    background-color: yellow;
    position: relative;
  }
  .child {
    width: 200px;
    height: 200px;
    background-color: aqua;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  }
</style>