原文引用自:
https://css-tricks.com/centering-css-complete-guide/#center-horizontally
Centering in CSS: A Complete Guide
如何进行元素居中?不是太难,而是方式太多,很多时候会面临选择综合症。所以,让我们用决定树的方式来把事情变得简单些吧!
水平居中:
是行内元素吗?
.center-children {
text-align: center;
}
是块级元素吗?
.center-me {
margin: 0 auto;
}
是多个块元素吗?
在一行内居中:
.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.是行内元素吗?
是单行元素吗?
上下padding-bottom设置成一致的:
.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实现方式
.parent { display: flex; justify-content: center; align-items: center;}
4.grid实现方式
body, html { height: 100%; display: grid;}span { /* thing to center */ margin: auto;}
终于,可以把所有元素都居中啦!