| |
实现文本和 div 元素的垂直居中有以下几种常用方法:
.container {
height: 50px; /* 设置容器高度 */
line-height: 50px; /* 设置行高等于容器高度 */
}
.text {
display: inline-block;
vertical-align: middle;
}
这种方法适用于单行文本。将行高设置为容器高度,并将文本元素设置为 inline-block 并垂直居中。
.container {
display: table-cell;
vertical-align: middle;
height: 50px; /* 设置容器高度 */
}
.text {
display: inline-block;
}
这种方法可以用于多行文本。将容器设置为 table-cell 并设置 vertical-align: middle,文本元素设置为 inline-block。
.container {
position: relative;
height: 50px; /* 设置容器高度 */
}
.text {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
这种方法通过绝对定位和 transform 属性来实现垂直居中。容器设置 position: relative,文本元素设置 position: absolute 并通过 transform: translateY(-50%) 将其上移自身高度的一半。
.container {
display: flex;
align-items: center;
height: 50px; /* 设置容器高度 */
}
.text {
/* 无需额外样式 */
}
Flexbox 布局提供了 align-items: center 属性,可以轻松实现垂直居中。容器设置 display: flex 并设置 align-items: center,文本元素就会自动垂直居中。
.container {
display: grid;
align-items: center;
height: 50px; /* 设置容器高度 */
}
.text {
/* 无需额外样式 */
}
Grid 布局也提供了 align-items: center 属性来实现垂直居中。容器设置 display: grid 并设置 align-items: center,文本元素就会自动垂直居中。
这些都是常见的实现文本和 div 元素垂直居中的 CSS 方法,您可以根据具体需求选择合适的方式。
系列Course并未All上架,处于先行测试阶段