Search code examples
htmlcsssassuser-experience

CSS-only sticky header with background color transition when scrolling but no JS


I want to create the sticky header effect that you can see here on this JekyNewAge theme page, where the header menu is transparent as long as it hovers over the hero section, but will transition to a white background as soon as you scroll past this region.

The code is for a "No-JS" site, so solution must be pure CSS and no javascript.

Have been experimenting with various position: sticky setups and older ways to achieve stickiness, but without luck. There are many examples on the web on how to do this, but none so far that I found which does it without javascript. There's always some jQuery or other code snippet involved.

Note: My CSS is generated from SaSS document, so examples using this would be great too.

Maybe this is not possible.. I would very much appreciate your input!


Solution

  • I thought about it a little. I still don't think you can do the transition as in the example with pure css, but this is the kind of trick I was thinking about, which does have a transparent header over the hero that gets a solid background after it. Maybe it helps:

    body {
      margin: 0;
    }
    header {
      padding: 1rem 2rem;
      position: fixed;
      width: 100%;
      z-index: 2;
    }
    .hero {
      background: teal;
      color: white;
      padding: 4rem 2rem;
      position: relative;
      z-index: 1;
      color: rgba(255, 255, 255, .2);
      font-size: 3rem;
      text-align: center;
    }
    .header-bg {
      padding: 1rem 2rem;
      position: fixed;
      width: 100%;
      background: white;
      top: 0;
    }
    .content {
      background: lightgrey;
      padding: 2rem;
      min-height: 800px;
    }
    <header>Header</header>
    <div class="hero">HERO</div>
    <div class="header-bg">&nbsp;</div>
    <div class="content">Content</div>