gpt4 book ai didi

css - "background-positon:center"不适用于 "background-attachement:scroll"

转载 作者:太空宇宙 更新时间:2023-11-04 09:43:33 26 4
gpt4 key购买 nike

我正在制作一个带有正文背景的布局。我需要将它水平和垂直居中。为此,我使用 background-position:center。

 background-image:url('address');
background-repeat:no-repeat;
background-position:50% 50%;

但是,背景没有正确垂直定位:您只能在屏幕顶部看到一半的图像。在这里查看 link to codepen .

作为解决方案,我尝试使用具有不同尺寸和背景位置的图像:50% 50%。然后我仔细检查了其他背景相关选择器,发现如果我添加背景附件并将其从滚动到固定的默认值更改,则图像会正确居中。

谁能解释一下为什么会这样?

最佳答案

如果您没有为 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>

关于css - "background-positon:center"不适用于 "background-attachement:scroll",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39681251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com