水平居中

sankigan2019-3-21前端CSS

1、外边距

<div class="box"></div>
.box {
    width: 100px;
    height: 100px;
    background: #FCC;

    margin: 0 auto;
}

2、行内块

<div class="container">
    <div class="box"></div>
</div>
.container {
    text-align: center;
}
.box {
    width: 100px;
    height: 100px;
    background: #FCC;

    display: inline-block;
}

3、绝对定位

<div class="box"></div>
.box {
    width: 100px;
    height: 100px;
    background: #FCC;

    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

4、Flex

<div class="container">
    <div class="box"></div>
</div>
.container {
    display: flex;
    justify-content: center;
}
.box {
    width: 100px;
    height: 100px;
    background: #FCC;
}