css布局--水平垂直居中

2019-08-22  本文已影响0人  琉璃_xin

默认状态:

    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }

    .parent {
      background: pink;
      height: 300px;
    }

    .child {
      background: green;
    }
  <div class="parent">
    <div class="child">
      this is child
    </div>
  </div>
默认

如何使子元素水平垂直居中呢?

  1. 子元素固定宽高的情况
    .parent{
      position: relative;
      top: 0;
      left: 0;
    }
    .child{
      position: absolute;
      top: 50%;
      left: 50%;
      width: 50px;
      height: 50px;
      margin-top: -25px;
      margin-left: -25px;
    }
    .parent {
      position: relative;
      top: 0;
      left: 0;
    }

    .child {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 50px;
      height: 50px;
      transform: translate(-50%, -50%)
    }
   .parent {
      position: relative;
      top: 0;
      left: 0;
    }

    .child {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      width: 50px;
      height: 50px;
    }
  1. 子元素宽高不定
    .parent {
      position: relative;
      top: 0;
      left: 0;
    }

    .child {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%)
    }
  .parent{
      display: flex;
      justify-content: center;
      align-items: center;
    }
居中
上一篇下一篇

猜你喜欢

热点阅读