佈局 —— 上下左右居中

html結構:html

<div class="main">
    <div class="content"></div>
</div>

 

一. 子元素絕對定位,left和top都設置爲50%,再設置margin-left和margin-top爲-1/2寬度、-1/2高度。此種狀況適用於寬度高度固定的狀況佈局

.main {
    width: 400px;
    height: 400px;
    background: #eee;
    position: relative;
}
.content {
    background: #ccc;
    width: 200px;
    height: 200px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -100px;
    margin-top: -100px;
}

 

二. transform,原理同方法一,此種方法可用於寬度高度不固定的狀況flex

.main {
    width: 400px;
    height: 400px;
    background: #eee;
    position: relative;
}
.content {
    background: #ccc;
    width: 200px;
    height: 200px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

 

三. flex佈局,父元素設置兩條軸上居中對齊方式spa

.main {
    width: 400px;
    height: 400px;
    background: #eee;
    display: flex;
    justify-content: center;
    align-items: center;
}
.content {
    background: #ccc;
    width: 200px;
    height: 200px;
    display: inline-block;
}

 

此外,設置文字垂直對齊還可使用line-height=父元素高度、table-cell方式。使用table-cell須要設置父元素display:tablecode

.main {
    width: 400px;
    height: 400px;
    background: #eee;
    display: table;
}
.content {
    background: #ccc;
    width: 200px;
    height: 200px;
    display: table-cell;
    vertical-align: middle;
}
相關文章
相關標籤/搜索