Reputation: 1244
I have some HTML set up like this:
<div class="mediasection large">
<div class="cover" style="background-image: url(/media/images/panorama.jpg);"></div>
<div class="overlay">Welcome!</div>
</div>
The cover element is uses background-attachment: fixed;
to create a parallax effect. What I'm trying to achieve is have the overlay element behave the same way, where the text in it is fixed to the viewport, but still contained inside the mediasection div, so that when the user scrolls the page the cover and overlay stay in the same position, but disappear as the mediasection element goes out of view.
Is there any way to achieve this?
tl;dr; Some sort of background-attachment: fixed;
to regular elements, not just the background.
Thanks!
Upvotes: 2
Views: 76
Reputation: 1244
I have found a jQuery based solution myself. I'm still not a fan of relying on JavaScript, so any other answers are welcome, but it works.
Here it is:
var oldScroll = 0;
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var scrollOffset = scroll - oldScroll;
// Overlay positions
var offset = $(".overlay").offset();
$(".overlay").offset({top: offset.top + scrollOffset});
oldScroll = scroll;
});
This offsets the overlay while scrolling.
But as I said, other answers are welcome.
Upvotes: 0
Reputation: 762
Honestly, I think the easiest way is to just to use photoshop / [your favourite image editing software] to put the overlay text over the background image. I made this jsfiddle which hopefully demonstrates your desired behavior.
<div class="media-screen">
<h1 class="sr-only">Overlay Text</h1>
<p class="sr-only">With an interesting paralax effect</p>
</div>
Where sr-only
is a class that hides elements visually while maintaining screen reader accessibility
.media-screen {
position: relative;
height: 250px;
background-image: url('path/to/your/image.png');
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
}
.sr-only {
position: absolute;
overflow: hidden;
clip: rect(0 0 0 0);
height: 1px; width: 1px;
margin: -1px; padding: 0; border: 0;
}
/*Example media query for view port width*/
@media screen only and (min-width: 1024px){
.media-screen {
background-image: url('path/to/your/image-large.png');
}
}
/* Example media query for view port orientation */
@media screen only and (orientation: portrait){
.media-screen {
background-image: url'path/to/your/image-narrow.png');
}
}
Note: Embedding content in the background image obviously means that the content is not interactive so this is only really any good for basic display elements.
Upvotes: 2