Horizontally 水平居中
-
内联元素
text-align: center;
-
块级元素
margin: 0 auto;
-
多个块级元素
display: flex;
justify-content: center;
Vertically 垂直居中
-
内联元素中单行文字
给定相同padding
padding-top: 30px;
padding-bottom: 30px;
-
文字垂直居中
height: 100px;
line-height: 100px;
white-space: nowrap;
-
内联元素中多行文字
<table>
<tr>
<td>
I'm vertically centered multiple lines of text in a real table cell.
</td>
</tr>
</table>
table布局下文字默认垂直居中
/* default is vertical-align: middle; */
方法二 display:table-cell
<div class="center-table">
<p>I'm vertically centered multiple lines of text in a CSS-created table layout.</p>
</div>
body {
background: #f06d06;
font-size: 80%;
}
.center-table {
display: table;height: 250px; background: white; width: 240px; margin: 20px;
}
.center-table p { display: table-cell;margin: 0;background: black;color: white;padding: 20px;
border: 10px solid white;vertical-align: middle;
}
方法三 flex 布局
display: flex;
justify-content: center;
flex-direction: column;
方法四 伪类 vertical-align
<div class="ghost-center">
<p>I'm vertically centered multiple lines of text in a container. Centered with a ghost pseudo element</p>
</div>
body {
background: #f06d06;
font-size: 80%;
}
div {
background: white;
width: 240px;
height: 200px;
margin: 20px;
color: white;
resize: vertical;
overflow: auto;
padding: 20px;
}
.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;
}
块级元素
-
已知宽高
.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; */
}
-
未知宽高
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
-
flex大法
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
水平垂直居中
- 已知元素宽高
.parent {
position: relative;
}
.child {
width: 300px;
height: 100px;
padding: 20px;
position: absolute;
top: 50%;
left: 50%;
margin: -70px 0 0 -170px;
}
- 未知元素宽高
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- flex大法
.parent {
display: flex;
justify-content: center;
align-items: center;
}
- grid布局
<span>
I'm centered!
</span>
body, html {
height: 100%;
display: grid;
}
span {
margin: auto;
}