5种简单有效的CSS实现方法
在网页设计中,将文字在容器中水平垂直居中是一个常见的需求。本文将介绍5种最常用且兼容性良好的实现方法,帮助您轻松解决居中问题。
/* CSS */
.demo {
display: flex;
align-items: center;
justify-content: center;
height: 150px;
}
.demo-box {
text-align: center;
}
/* CSS */
.demo {
display: grid;
place-items: center;
height: 150px;
}
/* CSS */
.demo {
position: relative;
height: 150px;
}
.demo-box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
/* CSS */
.demo {
display: table-cell;
vertical-align: middle;
text-align: center;
height: 150px;
width: 100%;
}
/* CSS */
.demo-box {
line-height: 100px; /* 与高度相同 */
height: 100px;
text-align: center;
}