Transitioning Divs

Hey,

So I have put together a nav bar at the top of my page, and made it sticky using

CSS:

/* NavBar Sticky */ 
.content {
  padding: 16px;
}
.sticky {
  position: fixed;
  top: 0;
  width: -webkit-fill-available;
}
.sticky + .content {
  padding-top: 0;
}

JS:

// When the user scrolls the page, execute myFunction
window.onscroll = function() {StickyFunction()};

// Get the navbar
var navbar = document.getElementById("navbar");

// Get the offset position of the navbar
var sticky = navbar.offsetTop;

// StickyNavBar
function StickyFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}

The slight issue is however that the rest of the page will move to fill the space. As seen below

So, I’m mostly looking for some guidance to transition the div moving up to the where the nav bar was originally located,

or if anyone has a simpler idea that would be great!

Since it can appear very choppy, if you are too slowly scroll, if you need any extra information, about the

  • css,
  • js
  • html

I’m more than happy to help.
Note:
( I have already attempted to use WW3 schools, if you find a link that would be helpful as well! :grin: )

Many Thanks,

Tom

Configuring padding-top should prevent the snapping. The number should be based on the navbar size and paddings.

Edit(s).

Found it: W3Schools Tryit Editor

In this concrete example, the value is a sum of navbar height and .content padding.
Let’s say I increase the height to 80px and the padding to 20px. That makes 100px the appropriate value.

2 Likes

Thankyou ever so much,

I feel like a clown, it was such an easy fix and its why you don’t copy something and expect it to work, I ended up having to just change the class name to.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.