一、使用 line-height 實現垂直居中
使用 line-height 屬性設置行高等於元素高度即可實現單行文本的垂直居中。
.container { height: 100px; line-height: 100px; }
如果需要實現多行文本的垂直居中,可以使用偽元素和 transform。
.container { position: relative; } .container::before { content: ''; display: inline-block; vertical-align: middle; height: 100%; } .text { display: inline-block; vertical-align: middle; transform: translateY(-50%); }
二、使用 flexbox 實現垂直居中
使用 flexbox 可以輕鬆實現父容器內元素的垂直居中。
.container { display: flex; align-items: center; /* 垂直居中 */ }
如果需要水平和垂直居中,可以使用 justify-content 和 align-items。
.container { display: flex; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ }
三、使用 table-cell 實現垂直居中
將元素設置為 display: table-cell 和 vertical-align: middle 即可實現垂直居中。
.container { display: table-cell; vertical-align: middle; height: 100px; /* 需要設置高度 */ }
四、使用 grid 實現垂直居中
使用 grid 可以輕鬆實現父容器內元素的垂直居中。
.container { display: grid; place-items: center; /* 水平居中和垂直居中 */ }
五、使用 position 和 transform 實現垂直居中
將元素設置為 position: absolute 和 top: 50%,再使用 transform: translateY(-50%) 即可實現垂直居中。
.container { position: relative; } .text { position: absolute; top: 50%; transform: translateY(-50%); }
綜上所述,CSS 實現文本的垂直居中有多種方法可選,根據不同需求選擇不同的實現方法即可。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/198381.html