html+css 將水平居中與垂直居中的幾種辦法

示例代碼:

<style>
    .box {
        width: 200px;
        height: 200px;
        background-color: red;
    }

    .inner {
        width: 100px;
        height: 100px;
        background-color: white;
    }
</style>
<body>
    <div class="box">
        <div class='inner'>
            居中
        </div>
    </div>
</body>

水平居中

1.<center>標籤
最簡單的方法,只需要在<div>外加上<center>就可以讓<div>水平居中:
代碼:

<body>
    <div class="box">
        <center>
            <div class='inner'>
                居中
            </div>
        </center>
    </div>
</body>

效果:
<center>標籤水平居中
2.margin法
<div>的 margin (外邊距)屬性設置成 “0 auto” 就可以居中
代碼:

.inner {
    width: 100px;
    height: 100px;
    background-color: white;
    margin: 0 auto;
}

效果:
margin
3.絕對位置法
<div>設置成絕對佈局,然後用left或right移動<div>到中間,由於元素的座標原點是左上角,所以爲了居中,要移回半個<div>寬度的距離。
可以用margin-left:[1/2寬度]px或者transform: translate(-50%,0)實現
需要注意的是使用這種方法時,必須定義了位置佈局方式。
代碼:

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: red;
}

.inner {

    width: 100px;
    height: 100px;
    background-color: white;
    position: absolute;
    left: 50%;
    margin-left: -50px;
}

效果:
絕對佈局法

垂直居中

1.margin法
垂直居中也可以用margin實現,同樣需要聲明佈局方式。
代碼:

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: red;
}

.inner {
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: white;
    margin: auto;
    top: 0;
    bottom: 0;
}

效果:
margin垂直居中
2.絕對位置法
和水平居中一樣 把left改爲top即可
代碼:

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: red;
}

.inner {
    width: 100px;
    height: 100px;
    background-color: white;
    position: absolute;
    top: 50%;
    margin-top: -50px;
}

效果:
絕對位置垂直居中

同時居中

1.margin法
只需margin:auto; , 然後topleftrightbottom 設置爲相同值即可
代碼:

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: red;
}

.inner {
    width: 100px;
    height: 100px;
    background-color: white;
    position: absolute;
    margin: auto;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
}

效果:
margin 同時居中
2.絕對位置法
將水平居中垂直居中同時使用即可。
代碼:

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: red;
}

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

效果:
絕對位置同時居中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章