固定背景图片

3
我很好奇如何在一个固定的div中创建背景图像。当您向下(或向上)滚动时,图像保持不变,但内容会流过div。这是一个网站,它可以做到我试图解释的事情,以便更好地描述我的问题。jWebMedia 我一直认为这样的网站非常吸引人,想知道如何开发它。如果您知道任何涵盖此内容的好文章,那就太棒了。
感谢您所有的帮助!
3个回答

6
background:url('http://yoururl');    
background-size: cover;
background-attachment: fixed;

完美。正是我想要实现的。谢谢你的帮助。 - user3412963

1

固定定位元素

fixed 该元素相对于浏览器窗口进行定位。

/*only for this sample*/
body{
  margin:0;
}
div{
  width:100%;
  height:1000px;
  background:green;
}
nav{
  position:fixed;
  top:0;
  width:100%;
  height:40px;
  background:grey;
}
<div>
<nav></nav>
</div>

固定背景图像

CSS background-attachment 属性

fixed 背景相对于视口固定不动

/*only for this sample*/
body{
  margin:0;
}

.fixed{
  width:100%;
  height:2000px;
  background-image:url(http://assets3.whicdn.com/assets/registration/reg_wall/Header-Find-your-inspiration.jpg);
  background-size:cover;
  background-attachment:fixed;
}
.scroll{
  position:absolute;
  width:50px;
  height:50px;
  margin:20px;
  background:orange;
}
<div class="fixed">
  <div class="scroll"></div>
</div>


0
这些实际上就是你在问题标题中所说的 - 固定背景图片background-attachment:fixed 将背景图像相对于 视口 固定 - 当滚动具有此类背景图像的元素进入和退出视口时,就会产生此效果,就是这么简单。

“background-position: fixed”不存在。 - user3790069
1
@user3790069:你说得对,我当然是指background-attachment。已经编辑过了。 - CBroe
@mitch:那么你到底是什么意思?特别是因为你“好奇如何在固定的div中创建背景图像”,现在已经接受了几乎实现这一目标的答案。 - CBroe
1
@CBroe 您是正确的,真抱歉。我本以为 CSS 还有更多内容,但在我尝试了一下 CSS 之后,发现只需要使用 background-attachment 即可。 - user3412963
就像我之前所说的那样,这其实非常简单。虽然在被接受的答案中提到的 background-size 属性可以很方便地自动调整背景图像以适应元素尺寸,但你可能也想了解一下它所提供的其他可能性(https://developer.mozilla.org/en-US/docs/Web/CSS/background-size)。 - CBroe

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