HTML代码

  1. <div class="wrap">
  2. <div class="box"></div>
  3. </div>

flex

  1. .wrap {
  2. width: 300px;
  3. height: 300px;
  4. background-color: pink;
  5. display: flex;
  6. justify-content: center;
  7. align-items: center;
  8. }
  9. .box {
  10. height: 100px;
  11. width: 100px;
  12. background-color: plum;
  13. }

table-cell

.wrap {
    width: 300px;
    height: 300px;
    background-color: pink;

    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

.box {
    height: 100px;
    width: 100px;
    background-color: plum;

    display: inline-block;
}

margin, transform

.wrap {
    width: 300px;
    height: 300px;
    background-color: pink;

    /* 解决外边距塌陷:加 border 或者overflow: hidden; */
    border: 1px solid red;

}

.box {
    height: 100px;
    width: 100px;
    background-color: plum;

    margin: 50% auto;
    transform: translateY(-50%);
}

inline-block, vertical-align

.wrap {
    width: 300px;
    height: 300px;
    background-color: pink;

    text-align: center;
    line-height: 300px;
}

.box {
    height: 100px;
    width: 100px;
    background-color: plum;

    /* 重新设置子元素的行高,否则会继承父元素的行高 */
    line-height: 100px;
    display: inline-block;
    /* middle 将元素放置在父元素的中部 */
    vertical-align: middle;
}

absolute, 负margin

.wrap {
    width: 300px;
    height: 300px;
    background-color: pink;

    position: relative;
}

.box {
    height: 100px;
    width: 100px;
    background-color: plum;

    position: absolute;
    left: 50%;
    top: 50%;
    /* 宽高的一半 */
    margin-left: -50px;
    margin-top: -50px;
}

absolute,margin:auto

.wrap {
    width: 300px;
    height: 300px;
    background-color: pink;

    position: relative;
}

.box {
    height: 100px;
    width: 100px;
    background-color: plum;

    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
}

absolute,transform

.wrap {
    width: 300px;
    height: 300px;
    background-color: pink;

    position: relative;
}

.box {
    height: 100px;
    width: 100px;
    background-color: plum;

    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

grid

.wrap {
    width: 300px;
    height: 300px;
    background-color: pink;

    display: grid;
}

.box {
    height: 100px;
    width: 100px;
    background-color: plum;

    align-self: center;
    justify-self: center;
}