< Back to Code

Sticky CSS

				
					.sticky {
  position: sticky;
  top: 0;

  background-color: #0ebac5;
  color: white;
  text-transform: capitalize;
  text-align: center;
  font-size: 1.2rem;
  display: grid;
  place-content: center;
}

				
			

This is sample content to make page longer

The method above only works with parent container has enough height to scroll

.

,

,

,

,

,

,

,

,

,

,

,

,

,

,

,

If you want to make the sticky inside a container but use for whole page. You should use javascript.

				
					<style>
  body {
    height: 2000px; /* Just for demonstration */
  }
  .fixed {
    position: relative; /* Initially relative position */
    top: 0; /* To keep the div at the top */
    width: 200px; /* Adjust width as needed */
    height: 100px; /* Adjust height as needed */
    background-color: lightblue;
    border: 1px solid blue;
  }
  .fixed.fixed-position {
    position: fixed; /* Apply fixed position when scrolled */
  }
</style>

<div id="target" class="fixed">Fixed Div</div>

<script>
  window.addEventListener('scroll', function() {
    var targetDiv = document.getElementById('target');
    var targetOffset = targetDiv.getBoundingClientRect().top;
    var scrollPosition = window.pageYOffset || document.documentElement.scrollTop;

    if (scrollPosition >= targetOffset) {
      targetDiv.classList.add('fixed-position');
    } else {
      targetDiv.classList.remove('fixed-position');
    }
  });
</script>
				
			
Fixed Div

vi

© Copyright by JAYbranding – All rights reserved.