元素垂直水平居中

215 阅读1分钟

html代码

<div class="wrap">
    <div class="inner"></div>
</div>

1. absolute+transform实现

style代码

<style>
    .wrap {
      border: 1px solid palevioletred;
      height: 200px;
      width: 200px;
      position: relative;
    }
    .inner {
      border: 1px solid palevioletred;
      width: 50%;
      height: 50%;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
    }
</style>

left:50%中的百分比是相对于定位父级的宽度。
translate:50%是相对于自身的宽度。
缺点:ie9以上支持

2. absolute+margin实现

style代码

<style>
    .wrap {
      border: 1px solid palevioletred;
      height: 200px;
      width: 200px;
      position: relative;
    }
    .inner {
      border: 1px solid palevioletred;
      width: 50%;
      height: 50%;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -25%;
      margin-top: -25%;
    }
</style>

left:50%中的百分比是相对于定位父级的宽度。
margin:50%是相对于自身的宽度。

3.absolute+margin:auto实现

  <style>
    .wrap {
      border: 1px solid palevioletred;
      height: 200px;
      width: 200px;
      position: relative;
    }
    .inner {
      border: 1px solid palevioletred;
      width: 50%;
      height: 50%;
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      margin: auto;
    }
  </style>

3.flex+margin:auto实现

  <style>
    .wrap {
      border: 1px solid palevioletred;
      height: 200px;
      width: 200px;
      display: flex;
    }
    .inner {
      border: 1px solid palevioletred;
      width: 50%;
      height: 50%;
      margin: auto;
    }
  </style>

4.flex实现

  <style>
    .wrap {
      border: 1px solid palevioletred;
      height: 200px;
      width: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .inner {
      border: 1px solid palevioletred;
      width: 50%;
      height: 50%;
    }
  </style>