CSS元素水平垂直居中

130 阅读1分钟

直接步入正题:

1、使用绝对定位

    div{
      width: 200px;
      height: 200px;
      background-color: aqua;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
    }

translate 有个非常大的优点,使用 translate 并不会影响其他元素的位置;其属性值可以是具像素(px)也可以是百分比(%),需要注意的是在使用 %(百分比) 时是相对于自身的宽高来计算的;另外 translate 对行内元素没有作用

2、使用定位加margin

<body>
  <div class="father">
    <div class="son"></div>
  </div>
  <style>
    * {
      margin: 0;
    }

    .father {
      background-color: #bfa;
      width: 1000px;
      height: 500px;
      position: relative;
      margin: 100px auto;
    }

    .son {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      margin: auto;
    }
  </style>
</body>

3、使用display: table-cell;

flex布局也只是对元素可以设置垂直居中,不作用于文本(默认情况下,图片,按钮,文字和单元格都可以用vertical-align属性)

<body>
  <div class="father">
    aaaaaaaa
  </div>
  <style>
    * {
      margin: 0;
    }

    .father {
      background-color: #bfa;
      width: 1000px;
      height: 500px;
      margin: 100px auto;
      display: table-cell;
      vertical-align: middle;
      text-align: center;
    }

    .son {
      width: 100px;
      height: 100px;
      background-color: red;
    }
  </style>
</body>