1. 程式人生 > >div 居中

div 居中

splay tran transform ems abs css play 內容 position

方法1 margin

.box{
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
}           

方法2 CSS3 transform-translate

.box {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

方法3 flex

.box {
    display: flex;
    background-color: red;
    height: 400px;
    width: 400px;
    align-items: center;
    justify-content: center;
}

.box2 {
    height: 100px;
    width: 100px;
    background-color: pink;
}

<div class="box">
    <div class="box2">
    </div>
</div>

方法4 轉換為inline

.box {
    background-color: red;
    height: 400px;
    width: 400px;
    text-align: center;
    line-height: 400px;
}

.box2 {
    display: inline;
    background-color: pink;
}
<div class="box">
    <div class="box2">
        內容內容
    </div>
</div>

div 居中