元素居中大全

原文引用自:
https://css-tricks.com/centering-css-complete-guide/#center-horizontally

Centering in CSS: A Complete Guide

如何進(jìn)行元素居中?不是太難,而是方式太多,很多時(shí)候會(huì)面臨選擇綜合癥。所以,讓我們用決定樹(shù)的方式來(lái)把事情變得簡(jiǎn)單些吧!

水平居中:

是行內(nèi)元素嗎?

.center-children { 
    text-align: center;
}

是塊級(jí)元素嗎?

.center-me {

  margin: 0 auto;

}

是多個(gè)塊元素嗎?

在一行內(nèi)居中:

.inline-block-center {

  text-align: center;

}

.inline-block-center div {

  display: inline-block;

  text-align: left;

}

OR:

.flex-center {

  display: flex;

  justify-content: center;

}

多個(gè)塊級(jí)元素居中:

main div {

  background: black;

  margin: 0 auto;

  color: white;

  padding: 15px;

  margin: 5px auto;

}

main div:nth-child(1) {

  width: 200px;

}

main div:nth-child(2) {

  width: 400px;

}

main div:nth-child(3) {

  width: 125px;

}

垂直居中

1.是行內(nèi)元素嗎?

是單行元素嗎?
上下padding-bottom設(shè)置成一致的:

.link { padding-top: 30px; padding-bottom: 30px;}

OR:

trick使元素的line-height和height相同:

.center-text-trick { height: 100px; line-height: 100px; white-space: nowrap;}

是多行元素嗎?

table:vertical-align: middle;

flexbox:.flex-center-vertically { display: flex; justify-content: center; flex-direction: column; height: 400px;}

2.是塊級(jí)元素嗎?

已知元素的height:

.parent { position: relative;}.child { position: absolute; top: 50%; height: 100px; margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */}

未知元素的height:

.parent { position: relative;}.child { position: absolute; top: 50%; transform: translateY(-50%);}

flex模型:

.parent { display: flex; flex-direction: column; justify-content: center;}

水平垂直居中

1.固定寬高的元素

.parent { position: relative;} .child { width: 300px; height: 100px; padding: 20px; position: absolute; top: 50%; left: 50%; margin: -70px 0 0 -170px;}

2.非固定寬高的元素

.parent { position: relative;}.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);}

3.flex實(shí)現(xiàn)方式

.parent { display: flex; justify-content: center; align-items: center;}

4.grid實(shí)現(xiàn)方式

body, html { height: 100%; display: grid;}span { /* thing to center */ margin: auto;}

終于,可以把所有元素都居中啦!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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