如何将背景图片固定在div内部

18

我发现了一个相当奇怪的问题,我认为我知道如何解释它;我只是不知道如何修复它!

我有一个带有div#container(高度为100%min-height(IE的高度))的页面,其中包含标题、“page-content”和页脚。 div#container的背景图应该是固定的(而不是固定位置,而是 background-attachment: fixed 使图片跟随滚动)。

问题是,当CSS中添加固定附件的背景标签时,背景图片现在位于div外部。

CSS如下:(没有background-attachment: fixed;

div#container {
    position:relative;
    width:900px;
    margin:0 auto;
    background-color: #ccffff;
    background-image: url("pics/sign.jpg");
    background-repeat: no-repeat;
    background-position: right top;

    height:auto !important;
    height:100%;

    min-height:100%;
}

margin:0 auto;用于居中div,而第一个height:中的!important作用是使IE忽略该特定高度标签。如果要使用min-height: 100%则必须这样做。

当我添加了这个...

div#container {
    position:relative;
    width:900px;
    margin:0 auto;
    background-color: #ccffff;
    background-image: url("pics/sign.jpg");
    background-attachment: fixed; //This is what is added to the code-sample
    background-repeat: no-repeat;
    background-position: right top;

    height:auto !important;
    height:100%;

    min-height:100%;
}

背景图片在

外面移动了。让我解释一下: 背景图像中唯一可见的部分是仍在
内部的部分,但部分图像已经移到
之外,现在不可见了。

简而言之...

当背景图片被固定时,它部分隐藏并在

外移动。该图片位置在浏览器窗口的右上角,而非
的右上角。

希望你们能帮帮我!

5个回答

17

这种行为其实是正确的。任何使用attachment: fixed属性的背景将与视口相对应,而不是与应用该属性的元素相对应。这实际上是Eric Meyer的Complex Spiral演示的基础。


3
有没有什么变通方法可以导致我想要的“错误行为”? :) - Latze
2
没有发现任何相关的内容。抱歉 :-( - Ryan Kinal
1
我也想要一个解决方案。我认为他不是在问为什么会发生这种情况,而是在问如何将滚动图像固定到一个 div 中。 - Ryan Chatterton
而且,目前还没有办法做到这一点。这个答案就是原因。 - Ryan Kinal

4

虽然你无法在

内固定背景位置,但最简单的解决方法是创建与你的图片相同大小的
。将图片设置为背景,并将其设置为position:absolute,放置在要放置它的
的右上角,使用right:0px;top:0px。请确保父
position:relative,否则它不会绝对定位在该
中。


0

没有足够的积分来评论上面的解决方法。虽然您可以为div使用background-attachment: fixed,但图像仍然附加到视口,并且您只能看到图像的一部分。如果您想要显示完整的图像,则没有多大用处。


1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

-1
你可以尝试添加background-origin属性,也许border-box值可以解决你的问题。此外,你可能想要定义background-size,记住covercontain是支持的并且非常有用。

-1

这是一个大约10年前的问题,但人们可能仍然会在这里寻找解决方法,就像我一样。

CSS的background-attachment属性来拯救了我们。

在这里检查工作的CodePen

代码片段如下:

.fixed {
  background: url('http://lorempixel.com/800/800/');
  background-attachment: fixed;
height: 400px;
  width: 50%;
  max-width: 600px;
  margin: 32px auto;
}
.extra-space {
  margin-bottom: 100px;
  margin-top: 100px;
}
<div class="extra-space">
</div>
<div class="fixed"><h1>This is my heading</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<div class="extra-space">
</div>


问题在于当相关的 div 不在中心位置时,background-attachment:fixed 无法正常工作。正如 @Josh Stodola 所回答的那样,图像会固定在视口上,而不是预期的 div 上。 - contemplator

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接