0

I have a sticky header with a scrollable table and background gradient. I would like the sticky header to have the same background as the body (i.e. a gradient which depends on how far you've scrolled down), but without the table showing through.

Here is my solution using JQuery (JSFiddle), which recalculates the start and end colors of the header gradient as the window scrolls. Is there a CSS-only solution, perhaps to make the portion of the table underneath the header invisible, or to force the header to share the gradient of the background?

HTML

<div id="container">
    <header>Hello world!</header>
    <table>
        <tr><td></td><td></td><td></td></tr>
        <tr><td></td><td></td><td></td></tr>
        <tr><td></td><td></td><td></td></tr>
        <tr><td></td><td></td><td></td></tr>
        <tr><td></td><td></td><td></td></tr>
        <tr><td></td><td></td><td></td></tr>
    </table>
</div>

CSS

body {
    background: linear-gradient(white, black)
}
header {
    position: fixed;
    font-size: 72px;
    width: 480px;
}
td {
    border: 1px solid black;
    width: 200px;
    height: 200px;
}

JQuery

$(function() {
    function updateGradient() {
        var header = $('header');
        var top = $(window).scrollTop();
        var bottom = header.outerHeight() + top;
        var totalHeight = $('#container').height();
        top = Math.round(255 * (1 - top / totalHeight));
        bottom = Math.round(255 * (1 - bottom / totalHeight));
        var gradient = 'linear-gradient(rgb(' + top + ',' + top + ',' + top + '), rgb(' + bottom + ',' + bottom + ',' + bottom + '))';
        header.css('background', gradient);
    }
    $(window).scroll(function() {
        updateGradient();
    });
    updateGradient();
});
1''
  • 26,823
  • 32
  • 143
  • 200
  • I'm afraid this cannot be done without using javascript: http://stackoverflow.com/questions/13128079/how-to-hide-content-that-is-scrolled-under-a-transparent-div – Valentin Mercier Jul 06 '14 at 22:10
  • However you can still consider wrapping your table inside a scrollable `div` which is positioned under your fixed header – Valentin Mercier Jul 06 '14 at 22:13
  • Thanks @ValentinMercier. In my actual case, the gradient extends both above and below the area of the table, so your second comment is not an option. However, I'll accept your first comment as an answer in a couple of days if nobody else offers a solution. – 1'' Jul 06 '14 at 23:01

0 Answers0