原文引用自:
https://css-tricks.com/centering-css-complete-guide/#center-horizontally
Centering in CSS: A Complete Guide
如何進(jìn)行元素居中惩淳?不是太難稚补,而是方式太多,很多時候會面臨選擇綜合癥茴晋。所以乘瓤,讓我們用決定樹的方式來把事情變得簡單些吧蝴蜓!
水平居中:
是行內(nèi)元素嗎运授?
.center-children {
text-align: center;
}
是塊級元素嗎荧关?
.center-me {
margin: 0 auto;
}
是多個塊元素嗎?
在一行內(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;
}
多個塊級元素居中:
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.是塊級元素嗎无蜂?
已知元素的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實現(xiàn)方式
.parent { display: flex; justify-content: center; align-items: center;}
4.grid實現(xiàn)方式
body, html { height: 100%; display: grid;}span { /* thing to center */ margin: auto;}
終于,可以把所有元素都居中啦蒙谓!