我有一个简单的片段:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body id="background-image"
style="background-image: url('background.jpg');" >
<div class="container">
wii jlkjkljkl fjkl jlkfsjlkfj klsajfkl sajkl jfklasj kfjsakl jlkfajs klfjlkasj fklasj klfjsakl lkfas
</div>
</body>
</html>css.css的内容如下:
#background-image {
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
background-position: center center;
}
.container {
display: flex;
align-items: center;
justify-content: center;
}我不能在屏幕中央显示文本。它是水平的,但不是垂直的。也就是说,我看到一个背景图像,文本水平地居中在图像的顶部。我想把文字放在中间。
怎么了?我认为flex和align-items:center的结合足以实现这一点。
发布于 2021-01-27 14:42:14
给body一个高度的100vh和container的height of 100%来实现你想要的。
为什么会这样?
因为你的身体需要这个显式的高度来伸展到视口高度的100%,而你的容器高度将是100%,也就是100 be。现在,您的弹性样式将适用于它应该是。
早些时候,容器并没有延伸到整个页面的高度。
#background-image {
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
background-position: center center;
height:100vh;
}
.container {
display: flex;
align-items: center;
justify-content: center;
height:100%;
}发布于 2021-01-27 14:48:18
你做得很完美,但你忘了一件小事。首先,需要将#背景图像容器的高度设置为100 to。
https://jsfiddle.net/dt5vxw6L/#&togetherjs=2DgR5IUFVN
#background-image {
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
background-position: center center;
background-color:red;
display: flex;
justify-content: center;
align-items: center;
**height: 100vh;**
}
.container {
background-color:green;
padding-top: auto;
padding-bottom: auto;
}https://stackoverflow.com/questions/65921213
复制相似问题