CSS实现元素水平或垂直居中的方法有很多种,以下是14种常见的实现方式:
- 使用flexbox布局
.parent {
display: flex;
justify-content: center;
align-items: center;
}
- 使用grid布局
.parent {
display: grid;
place-items: center;
}
- 使用绝对定位和transform
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- 使用绝对定位和margin:auto
.parent {
position: relative;
}
.child {
width: 50%;
height: 50%;
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
- 使用line-height(适用于单行文本)
.parent {
height: 100px;
line-height: 100px;
}
.child {
display: inline-block;
vertical-align: middle;
}
- 使用text-align和inline-block(适用于单行文本或图像)
.parent {
text-align: center;
}
.child {
display: inline-block;
vertical-align: middle;
line-height: normal; /* 重置line-height */
}
- 使用table-cell和margin(IE8+)
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child {
display: inline-block;
vertical-align: middle;
}
- 使用margin:auto(IE10+)
.parent {
display: -webkit-flex;
display: flex;
}
.child {
width: 50%;
margin: auto;
}
- 使用writing-mode和text-align(垂直居中)
.parent {
width: 100px;
height: 100px;
writing-mode: vertical-lr;
text-align: center;
}
.child {
display: inline-block;
vertical-align: middle;
writing-mode: horizontal-tb;
}
- 使用writing-mode和line-height(垂直居中)
.parent {
width: 100px;
height: 100px;
writing-mode: vertical-lr;
line-height: 100px;
}
.child {
display: inline-block;
vertical-align: middle;
}
- 使用writing-mode和text-align(水平居中)
.parent {
width: 100px;
height: 100px;
writing-mode: horizontal-tb;
text-align: center;
}
.child {
display: block;
vertical-align: middle;
}
- 使用writing-mode和margin(水平居中)
.parent {
width: 100px;
height: 100px;
writing-mode: horizontal-tb;
}
.child {
display: inline-block;
margin: auto;
}
- 使用transform和absolute定位(水平或垂直居中)
.parent {
position: relative;
}
.child {
position: absolute;
transform: translate(50%, 50%);
}