我有这个简单的代码片段:
<!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
的组合足以使这种情况发生。
让body
的高度为100vh
,container
的高度为height
的高度为100%
,以达到您想要的效果。
为什么?
因为你的身体需要明确的高度拉伸到viewport高度的100%,而你的容器高度将是100%,这也是100vh。现在,您的flex样式将按原样应用。
先前容器没有拉伸到整个页面的高度。
#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%;
}
你做得很完美,但是你忘了一件小事。首先你需要设置#background-image容器的高度,例如100vh。
https://jsfiddle.net/dt5vxw6L/, togetherjs = 2 dgr5iufvn
#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;
}