在 CSS 中,想要让字体垂直居中是一件比较麻烦的事情。而本文将教大家几种方法来解决这个问题。
/* 方法一:line-height */
.element {
height: 200px;
line-height: 200px;
}
/* 方法二:flexbox */
.parent {
display: flex;
justify-content: center;
align-items: center;
}
/* 方法三:table-cell */
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}
/* 方法四:transform */
.element {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
} 以上四种方法各有优缺点,可根据实际需求来选择适合的方法。需要注意的是,在使用 line-height 或者 table-cell 的方法时,需要给父元素一个固定的高度。