Search code examples
csscss-position

Make a bottom right fixed element rise above footer


I was wondering how I could make a div that I have fixed to the bottom right of my screen become unfixed once the page reaches the footer.

For example if my html is:

<div class="main" />
<div class="fixed" />
<div class="footer" />

And my css is:

.main {
    height: 100vh;
    background-color: aqua;
    width: 100vw;
}

.fixed {
    background-color: green;
    height: 200px;
    position: fixed;
    bottom: 0px;
    width: 200px;
}

.footer {
    background-color: brown;
    height: 300px;
    width: 100vw;
}

I would like to have my fixed div in the bottom until the footer starts to be revealed and then have it scroll on top of the footer. Should I use sticky positioning? If so how do I do that? If not is there a better solution? Thanks.


Solution

  • You can use position: sticky along with bottom: 0 to stick it to the bottom of the viewport (to answer your question of how). Since it's non-sticky location is right before the footer, it will rest naturally when the viewport reaches there.

    body {
      font-weight: bold;
      font-size: 24px;
      padding-bottom: 300px;
    }
    
    main * {
      padding: 10px;
      background-color: #ccc;
      border: 1px solid #000;
    }
    
    .content {
      min-height: 1000px;
    }
    
    .sticky {
      position: sticky;
      /* the important part - stick to the bottom */
      bottom: 0;
      border: 1px solid red;
      background-color: white;
    }
    <main>
      <div class="content">content</div>
      <div class="sticky">I'm sticky</div>
      <footer>footer</footer>
    </main>

    That being said, as mentioned in the comment by Will - should you use it? That depends on what browsers you support. If you need to support older browsers, you'll need a fallback and/or JavaScript to handle the positioning.