Reputation: 1816
I've created a parallax scrolling effect using only CSS. However I'm struggling to understand why it's actually working. Can someone help explain.
HTML
<div class="image"></div>
<section class="content">
<p>TEXT GOES HERE</p>
</section>
CSS
.image {
background: url('http://s28.postimg.org/v6mfcxbyl/galaxy.jpg') no-repeat fixed;
background-position: center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
min-height: 500px;
}
.content {
width: 100%;
max-width: 750px;
margin: 0 auto;
background: #fff;
box-sizing: border-box;
-moz-box-sizing: border-box;
position: relative;
z-index: 2;
background: #FFF;
width: 100%;
}
It looks like it has something to do with setting the background fixed on the image div.
Here's a working fiddle http://jsfiddle.net/pAjNr/
Upvotes: 1
Views: 251
Reputation: 51241
Setting the background to fixed will fix the background-image relative to the viewport, even when the element itself scrolls (see here with added border: Example 1 ).
You could as well position the .image
element itself with position:fixed
and add an offset for the .content
element: Example 2 to achieve exactly the same effect.
Upvotes: 1
Reputation: 27833
position:fixed
and background-attachment:fixed
mean that the element will not move in relation to the viewport. So however much you scroll, the title (position:fixed
) and the background image (background-attachment:fixed
) will not move. The thing that does move is the text (.content
) which doesn't have position:fixed
.
When the text crosses over the title, it has a higher z-index (and position:relative
so the z-index is not ignored) so it hides whatever is underneath it (the title).
Upvotes: 2
Reputation: 7444
Statically fixed or relatively (according to document) position of the background image will create the background effect.
The title is positioned fixed with a z-index
lower then the content this being covered by it on scroll.
The content below is just normal and on scroll it just covers all the fixed elements with lower z-index
.
Upvotes: 2