2

I want to divide my website into two parts: a header containing a large image, and a main part, containing other images, text, etc.

When I scroll the page, the large image on the header should scroll together with the main part. In a certain point, the image should become fixed, and the main part scroll behind it.

I have tried some different approaches, but I can’t get the right combination of position, display, top, etc to work.

That’s the closest I’ve got so far: https://jsfiddle.net/aor0abhf/

HTML

<body onscroll='scroll(event)'>
  <div class='top' id='top'><img src='http://www.vejanomapa.net.br/wp-content/uploads/2013/03/Maria-Fuma%C3%A7a-em-Tiradentes-MG.jpg'></div>
  <div class='bottom'>
    <div class='menu'>Menu</div>
    <div class='main'><img src='http://tvulavras.com.br/wp-content/uploads/2017/04/maria-fuma%C3%A7a.jpg'></div>
  </div>
</body>

Javascript

function scroll(e) {
    var T = document.getElementById('top');
    var imgH = T.clientHeight; // header image height
    var hH = 200; // fixed header height
    if (imgH-e.pageY > hH) { // image is scrolling
        T.style.top = '-'+e.pageY+'px';
        T.style.position = 'sticky';
    } else { // image should remain fixed
        T.style.top = '-'+(imgH-hH)+'px';
        T.style.position = 'fixed';
    }
}

CSS

html, body {
    margin:0;
}
body {
    overflow-y:scroll;
    overflow-x:hidden;
}
img {
    display:block;
}
.top {
    background:#FCC;
  display:block;
    top:0;
}
.bottom {
    display:flex;
    min-height:1500px;
    background:#CFC;
}
.menu {
    width:100px;
    background:#CCF;
}

But still there’s a glitch in the transition between scroll/fixed positions. And if the left menu (in light blue) could stick together, that would be great! (Maybe subject to another question?)