目录
- 水平居中
- 内联元素水平居中
- 块级元素水平居中
- 多个块级元素的水平居中
- 垂直居中
- 内联元素垂直居中
- 单行内联元素
- 多行内联元素
- 块级元素垂直居中
- 知道元素的height
- 不知道元素的height
- 子元素高度无所谓
- 能用Flex-box
- 内联元素垂直居中
- 水平且垂直居中
- 元素有固定宽高
- 元素没有固定宽高
- 能用Flex-box
- 能用Grid
水平居中
(1)内联元素水平居中
.center-children {
text-align: center;
}
(2)块级元素水平居中
.center-me {
margin: 0 auto;
}
(3)多个块级元素的水平居中
多元素水平排列
inline-block
法:
.father {
text-align: center;
}
.father .center-children {
display: inline-block;
}
flex
法:
.father {
display: flex;
justify-content: center;
}
多元素纵向排列
main {
margin: 20px 0;
}
main div {
margin: 0 auto;
}
main div:nth-child(1) {
width: 200px;
}
main div:nth-child(2) {
width: 400px;
}
main div:nth-child(3) {
width: 125px;
}
垂直居中
(1)内联元素垂直居中
① 单行内联元素
padding
法:
.link {
padding-top: 30px;
padding-bottom: 30px;
}
line-height
法:
.center-text-trick {
height: 100px;
line-height: 100px;
white-space: nowrap;
}
② 多行内联元素
table
法:
<table>
<tr>
<td>
I'm vertically centered multiple lines of text in a real table cell.
</td>
</tr>
</table>
table {
width: 240px;
height: 250px;
}
table td {
padding: 20px;
/* default is vertical-align: middle; */
}
display: table;
法:
<div class="center-table">
<p>I'm vertically centered multiple lines of text in a CSS-created table layout.</p>
</div>
.center-table {
display: table;
height: 250px;
width: 240px;
}
.center-table p {
display: table-cell;
margin: 0;
padding: 20px;
vertical-align: middle;
}
flex
法:
<div class="flex-center">
<p>I'm vertically centered multiple lines of text in a flexbox container.</p>
</div>
.flex-center {
height: 200px;
display: flex;
flex-direction: column;
justify-content: center;
resize: vertical; /* 允许用户在垂直方向上调整元素的大小 */
overflow: auto;
}
伪元素法:(在不确定父类高度时使用)
.ghost-center {
position: relative;
}
.ghost-center::before {
content: " ";
display: inline-block;
height: 100%;
width: 1%;
vertical-align: middle;
}
.ghost-center p {
display: inline-block;
vertical-align: middle;
}
(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%);
}
③ 子元素高度无所谓
main {
height: 300px;
width: 300px;
position: relative;
display: table;
}
main div {
display: table-cell;
vertical-align: middle;
}
④ 能用Flex-box
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
水平且垂直居中
(1)元素有固定宽高
.parent {
position: relative;
}
.child {
width: 300px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -150px;
}
(2)元素没有固定宽高
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
(3)能用Flex-box
.parent {
display: flex;
justify-content: center;
align-items: center;
}
(4)能用Grid
body, html {
height: 100%;
display: grid;
}
span { /* thing to center */
margin: auto;
}