CSS(层叠样式表)是一种用于描述HTML或XML(包括SVG、MathML等各种XML方言)文档样式的样式表语言。垂直居中是指将元素在父容器中垂直方向上居中对齐。
line-height
等于容器的高度。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vertical Centering</title>
<style>
.container {
height: 200px;
border: 1px solid black;
}
.text {
line-height: 200px;
}
</style>
</head>
<body>
<div class="container">
<span class="text">垂直居中的文本</span>
</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 Centering</title>
<style>
.container {
height: 200px;
border: 1px solid black;
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 Centering</title>
<style>
.container {
height: 200px;
border: 1px solid black;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class="container">
<img src="https://via.placeholder.com/150" alt="示例图片">
</div>
</body>
</html>
原因:
align-items: center
或justify-content: center
未设置。align-items: center
或justify-items: center
未设置。解决方法: 确保容器有明确的高度,并正确设置Flexbox或Grid的相关属性。
通过以上方法,可以有效地实现CSS中图片和文字的垂直居中,并解决常见的问题。
领取专属 10元无门槛券
手把手带您无忧上云