水平垂直居中常見方式總結

水平垂直居中常見方式總結

html結構爲:html

<div class="parent">
    <div class="child"></div>
</div>

 

(1)父元素相對定位,子元素關鍵在於設置爲絕對定位,margin:autoflex

.parent{
    width:400px;
    height:400px;
    background:#afa;
    position:relative;
}
.child{
    position:absolute;
    left:0;
    bottom:0;
    right:0;
    top:0;
    margin:auto;
    background:yellow;
    width:100px;
    height:100px;
}

(2)父元素相對定位,子元素絕對定位,且設置transform:translate(-50%,-50%)spa

.parent{
    width:400px;
    height:400px;
    background:#afa;
    position:relative;
}
.child{
    position:absolute;
    left:50%;
    top:50%;
    transform:translate(-50%,-50%);
    background:yellow;
    width:100px;
    height:100px;
}

(3)父元素設置爲display:flex;justify-content:center;align-items:centercode

.parent{
    width:400px;
    height:400px;
    display:flex;
    justify-content:center;
    align-items:center;
    background:#afa;
}
.child{
    width:100px;
    height:100px;
    background:yellow;
}

 (4)設置父元素display:table-cell;text-align:center;vertical-align:center;子元素:display:inline-block;orm

.parent{
    display:table-cell;
    width:400px;
    height:400px;
    background:#afa;
    text-align:center;
    vertical-align: middle;
}
.child{
    display:inline-block;
    width:100px;
    height:100px;
    background:yellow;
}
相關文章
相關標籤/搜索