CSS(层叠样式表)是一种用于描述HTML或XML文档样式的样式表语言。文字纵向居中是指将文本在容器内垂直方向上居中对齐。
line-height
属性。display: flex
和 align-items: center
。display: grid
和 align-items: center
。display: flex
和 align-items: center
。display: grid
和 align-items: center
。padding
或 margin
调整。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Single Line Vertical Center</title>
<style>
.container {
height: 200px;
border: 1px solid black;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class="container">
Centered 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>Multi Line Vertical Center</title>
<style>
.container {
height: 300px;
border: 1px solid black;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<p>This is a multi-line text that is vertically centered within the container.</p>
</div>
</body>
</html>
line-height
无法实现多行文本垂直居中?原因:line-height
只能用于单行文本的垂直居中,对于多行文本,它只会影响每一行的基线对齐,而无法实现整体的垂直居中。
解决方法:使用 display: flex
或 display: grid
结合 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>Multi Line Vertical Center with Flexbox</title>
<style>
.container {
height: 300px;
border: 1px solid black;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<p>This is a multi-line text that is vertically centered within the container.</p>
</div>
</body>
</html>
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云