Search code examples
cssnavbarsticky

Resize Sticky Element When in Final Position


I have a horizontal menu bar under a page banner. On the bar is a circular div. When user scrolls down the menu sticks to top of page. I am trying to figure out how to shrink the circular div when the menu bar hits the top. I'm not sure if this can be done with pure CSS or JS is needed.

.type1 {
  border-radius: 50%;
  width: 150px;
  height: 150px;
  background: yellow;
  border: 3px solid red;
  overflow: hidden;
  position: absolute;
  left: 300px;
  z-index: 1;
}

.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  z-index: 2;
}

.divbox2 {
  text-align: left;
  width: 1000px;
  height: 100px;
  background-color: red;
  position: absolute;
  left: 0px;
}
<div style="height:200px;background: green"></div>

<div class="sticky">

  <div class="divbox2"></div>
  <div class="type1"></div>
</div>

<img src="https://i.sstatic.net/8FkV2fTK.jpg">
<img src="https://i.sstatic.net/8FkV2fTK.jpg">

sticky navbar with circle


Solution

  • Here's a solution using JavaScript.

    Add an event listener to the pages scroll event that checks if we have scrolled past 200px (the height of your header), if true then we add a .shrink class to the parent container of the circle.

    Adjust the CSS such that there is a new circle style that is applied then the .shrink class is added. This is done with the .shrink .type1 selector.

    Check out the interactive demo and corresponding code below.

    document.addEventListener('scroll', event => {
      console.log(window.scrollY)
      if (window.scrollY > 200) {
        document.querySelector('.sticky').classList.add('shrink')
      } else {
        document.querySelector('.sticky').classList.remove('shrink')
      }
    })
    .sticky {
      position: -webkit-sticky;
      position: sticky;
      top: 0;
      z-index:2;
    }
    
    .divbox2 {
      text-align: left;
      width:1000px;
      height:100px;
      background-color:red;
      position: absolute;
      left: 0px;
    }
    
    .type1 {
      border-radius: 50%;
      width: 150px;
      height: 150px;
      background: yellow;
      border: 3px solid red;
      overflow:hidden;
      position: absolute;
      left: 300px;
      z-index: 1;
      
      transition: all 0.3s;
    }
    
    .shrink .type1 {
      height: 50px;
      width: 50px;
    }
    
    
            
    
    
       
    <div style="height:200px;background: green"></div>       
    <div class="sticky">  
       <div class="divbox2"></div>      
       <div class="type1"></div>    
    </div>
     
    <img src="https://www.bb2002.com/tillyimages/images/Terracotta Lego.jpg">
    <img src="https://www.bb2002.com/tillyimages/images/Terracotta Lego.jpg">