I've discovered a clever technique using a few lines of JavaScript:
Live demo on jsBin
var headerFixed = document.getElementById("headerFixed");
var headerClone = document.getElementById("headerClone");
headerClone.innerHTML = headerFixed.innerHTML; // Clone the header content (good for SEO)
function adjustHeaderOpacity(){
var topPos = headerClone.getBoundingClientRect().top; // Keep track of the clone's top position
headerFixed.style.opacity = topPos<0 ? 0 : 1; // Toggle original header opacity
headerClone.style.opacity = topPos<0 ? 1 : 0; // Toggle cloned header opacity
}
adjustHeaderOpacity(); // Execute when DOM is loaded
window.onscroll = adjustHeaderOpacity; // Execute on scroll
window.onresize = adjustHeaderOpacity; // Also execute on resize
The idea behind it:
+-- +----------------+-- (Viewport Top)
| | headerFixed | opacity:1; goes to 0 when the Clone reaches Viewport Top
h +----------------+
e | |
r | |
o +----------------+
| # headerClone | opacity:0; goes to 1 when it reaches Viewport Top
+-- +----------------+-- (Viewport Bottom)
| Content... |
⋮ ⋮
HTML structure:
<div id="hero">
<div id="headerFixed"><h1>Header</h1></div>
<div id="headerClone"></div>
</div>
<div id="content">Website template and content go here</div>
CSS styling:
html, body { height:100%; }
#hero{
height:100%;
}
#headerFixed {
position: fixed;
width: 100%;
}
#headerClone{
position:absolute;
bottom:0;
opacity:0;
width:100%;
}
Hint: if the explanation above is unclear, try adding different background-colors to all elements. It will help visualize what's happening.