我正在制作一个布局,在身体中有背景。我需要将它水平和垂直居中。为此,我使用了background-position:center。
background-image:url('address');
background-repeat:no-repeat;
background-position:50% 50%; 然而,背景没有正确地垂直放置:您只能在屏幕顶部看到图像的一半。在这里查看,link to codepen。
作为解决方案,我尝试使用不同大小和背景位置的图像: 50% 50%。然后我仔细检查了其他与背景相关的选择器,发现如果我添加了背景附加,并将其从默认值scroll更改为fixed,那么图像将正确居中。
有人能解释一下为什么会发生这种情况吗?
发布于 2016-09-25 20:28:48
如果你没有给body一个高度,就会发生这种情况,因为它的默认值是0。
body的高度是基于其内容的,而不是由背景图像设置的。
下面是一个示例,展示了您需要如何执行以下操作
html, body {
margin: 0;
height: 100%;
}
body {
background-image: url(http://placehold.it/200);
background-repeat: no-repeat;
background-position: center center;
}
有时,当需要给body一个高度时,以及当一个定位的div是一种选择时,它会产生其他问题
#bkgdiv {
position: absolute;
left: 0; top: 0; right: 0; height: 100vh;
background-image: url(http://placehold.it/200);
background-repeat: no-repeat;
background-position: center center;
}<div id="bkgdiv"></div>
因此,基于如何/如果你需要使用background-attachment: scroll和/或定位的div,这里有一个示例,展示了它们在滚动时的行为(以及可以播放的fiddle demo )。
html, body {
margin: 0;
height: 100%;
}
body {
background-image: url(http://placehold.it/200);
background-repeat: no-repeat;
background-position: center center;
background-attachment: scroll;
}
#bkgdiv {
position: absolute;
left: 0; top: 0; right: 0; height: 100vh;
background-image: url(http://placehold.it/180/0f0);
background-repeat: no-repeat;
background-position: center center;
}
#bkgdivfixed {
position: fixed;
left: 0; top: 0; right: 0; height: 100vh;
background-image: url(http://placehold.it/160/ff0);
background-repeat: no-repeat;
background-position: center center;
}<div id="bkgdiv"></div>
<div id="bkgdivfixed"></div>
<div style="width: 5px; height: 150vh; background: red; margin: 5px"></div>
发布于 2016-09-25 22:45:13
如果你想给body提供背景,这是非常简单的任务。
最初,您需要为body和html编写css。
html, body {
margin: 0;
height: 100%;
}下一步是你需要给正文提供背景css
body {
background-image: url(https://yt3.ggpht.com/-v0soe-ievYE/AAAAAAAAAAI/AAAAAAAAAAA/OixOH_h84Po/s900-c-k-no-mo-rj-c0xffffff/photo.jpg);
background-position: center;
background-repeat: no-repeat;
}好的,现在图像似乎是主体(屏幕)的中心,现在你可以使用background-size属性来调整大小。
background-size: cover;图像放大到足以覆盖整个屏幕。
background-size: contain;图像放大到屏幕的高度或宽度(较小)。
你可以给它固定的大小。
background-size: Xpx Ypx;https://stackoverflow.com/questions/39681251
复制相似问题