CSS 您如何在封面图片(如 medium.com)上滚动页面内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20872806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you scroll the page content over a cover image (like medium.com)?
提问by pandringa
I want to try to replicate the cover image's scroll effect found on medium.com (example: http://medium.com/@ev). As you scroll down the page, the cover photo stays fixed and the content scrolls over it, covering it up as you go. Does anyone know how to do this with CSS?
我想尝试复制在 medium.com 上找到的封面图像的滚动效果(例如:http://medium.com/@ev )。当您向下滚动页面时,封面照片保持固定,内容会滚动到它上面,并在您移动时将其覆盖。有谁知道如何用 CSS 做到这一点?
Thanks!
谢谢!
回答by jmore009
you can do this very simply by setting the background image on a body as fixed
and then using a div
with no color/image as a header.
您可以通过在主体上设置背景图像fixed
,然后使用div
没有颜色/图像作为标题来非常简单地做到这一点。
body{
background: url("image.JPG") no-repeat top center fixed;
background-size: cover;
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
UPDATE
更新
A better solution is to add it directly to the container you are targeting rather than the body
. In this case it's the header
更好的解决方案是将其直接添加到您所针对的容器而不是body
. 在这种情况下,它是header
.header{
background: url("http://upload.wikimedia.org/wikipedia/commons/8/86/Jefferson_Park_in_Chicago.JPG") no-repeat top center fixed;
background-size: cover;
height: 200px;
width: 100%;
margin: 0;
padding: 0;
color: white;
text-align: center;
font-size: 50px;
}
The results are identical but this way you don't need a container with a background color to cover up the image like the previous solution
结果是相同的,但是这样您就不需要像以前的解决方案一样使用带有背景颜色的容器来覆盖图像
回答by pandringa
It's quite simply:
很简单:
background-attachment:fixed;
On whatever you want your fixed background on.
在任何你想要固定背景的地方。
(example)
(例子)
But, on behalf of my personal experience. You could also consider a parallax scrolling library. It makes it feel more interactive, rather than a fixed background... There are a few JavaScript libraries to accomplish the scrolling effect (depending on how you want to trigger the effect). But, below are a few that I prefer.
但是,代表我个人的经验。您还可以考虑视差滚动库。它让它感觉更具交互性,而不是固定的背景......有一些 JavaScript 库可以实现滚动效果(取决于您想要如何触发效果)。但是,以下是我更喜欢的一些。
ParallaxJS(source)
ParallaxJS(源代码)
Creates a parallax effect based on mouse possition or the device's gyroscope(mobile tilting).
根据鼠标位置或设备的陀螺仪(移动倾斜)创建视差效果。
StellarJS(source)
StellarJS(源代码)
Creates a parallax effect based on scroll position. This is my most favorite choice out of both, because it's based on scrolling (I believe it supports mobile scrolling too). So you don't have to change most of your layout just to get the effect.
根据滚动位置创建视差效果。这是我最喜欢的选择,因为它基于滚动(我相信它也支持移动滚动)。因此,您不必为了获得效果而更改大部分布局。