CSS(Cascading Style Sheets)是一种用于描述HTML或XML(包括SVG、MathML等各种XML方言)文档样式的样式表语言。垂直居中是指将文本或元素在容器内垂直方向上居中对齐。
line-height 属性。display: flex 和 align-items: center。display: flex 和 align-items: center。display: grid 和 align-content: center。position: absolute 和 transform。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vertical Center Single Line Text</title>
<style>
.container {
height: 200px;
background-color: #f0f0f0;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class="container">
<p>垂直居中的单行文本</p>
</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>Vertical Center Multi-line Text</title>
<style>
.container {
height: 300px;
background-color: #f0f0f0;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class="container">
<p>这是垂直居中的<br>多行文本示例</p>
</div>
</body>
</html>line-height 无法垂直居中?原因:line-height 只能用于单行文本的垂直居中,如果文本是多行的,line-height 将无法实现垂直居中。
解决方法:使用 display: flex 和 align-items: center 或其他方法来实现多行文本的垂直居中。
position: absolute 和 transform 时,文本没有垂直居中?原因:可能是由于父元素没有设置 position: relative 或 position: absolute,导致 transform 的偏移量计算不正确。
解决方法:确保父元素设置了 position: relative 或 position: absolute。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vertical Center with Position and Transform</title>
<style>
.container {
position: relative;
height: 200px;
background-color: #f0f0f0;
}
.text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="container">
<p class="text">垂直居中的文本</p>
</div>
</body>
</html>