css垂直居中7種常用方法

image.png
image.png

居中元素寬高已知

1. absolute + margin auto

 .parent {
            position: relative;
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
        }
.child1 {
            background: tomato;
            width: 50px;
            height: 50px;
            /**關(guān)鍵代碼**/
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
        }

2.absolute + 負margin

.parent {
            position: relative;
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
        }
.child2 {
           background: tomato;
            width: 50px;
            height: 50px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -25px; /**寬度的一半**/
            margin-left: -25px;
        }

3.absolute + calc

.parent {
            position: relative;
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
        }
.child3 {
           background: tomato;
            width: 50px;
            height: 50px;
            position: absolute;
            top: calc(50% - 25px);
            left: calc(50% - 25px);
        }

居中元素寬高未知

4.absolute + transform

.parent {
            position: relative;
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
        }
.child4 {
           background: tomato;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

5.line-height + vertical-align

 .parent5 {
            width: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
            /**關(guān)鍵代碼**/
            line-height: 100px;
            text-align: center;
        }
 .child5 {
            background: tomato;
            /**關(guān)鍵代碼**/
            display: inline-block;
            vertical-align: middle;
            line-height: initial;
        }

6.flex布局

.parent6 {
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            margin: 0 auto;
            /**關(guān)鍵代碼**/
            display: flex;
            justify-content: center;
            align-items: center;
        }

7.flex + margin auto

.parent7 {
            width: 100px;
            height: 100px;
            border: 3px solid steelblue;
            /**關(guān)鍵代碼**/
            display: flex;
            margin: 0 auto;
        }
.child7 {
            margin: auto;
        }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容