CSS行高(line-height)是指文本行之间的垂直距离。通过设置行高,可以使文本在垂直方向上居中对齐。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS行高居中示例</title>
<style>
.center-text {
line-height: 50px; /* 设置行高 */
height: 50px; /* 设置容器高度 */
text-align: center; /* 水平居中 */
}
</style>
</head>
<body>
<div class="center-text">单行文本居中</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS行高居中示例</title>
<style>
.center-text {
line-height: 2; /* 设置行高 */
height: 100px; /* 设置容器高度 */
text-align: center; /* 水平居中 */
display: flex; /* 使用Flexbox布局 */
align-items: center; /* 垂直居中 */
}
</style>
</head>
<body>
<div class="center-text">
这是多行文本居中的示例。<br>
通过设置行高和使用Flexbox布局,可以实现多行文本的垂直居中。
</div>
</body>
</html>
原因:
解决方法:
align-items: center;
。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS行高居中示例</title>
<style>
.center-text {
line-height: 2; /* 设置行高 */
height: 100px; /* 设置容器高度 */
text-align: center; /* 水平居中 */
display: flex; /* 使用Flexbox布局 */
align-items: center; /* 垂直居中 */
}
</style>
</head>
<body>
<div class="center-text">
这是多行文本居中的示例。<br>
通过设置行高和使用Flexbox布局,可以实现多行文本的垂直居中。
</div>
</body>
</html>
领取专属 10元无门槛券
手把手带您无忧上云