Home >Web Front-end >CSS Tutorial >How to Animate or Shrink a Bootstrap Navbar on Scroll?
How to Animate or Shrink a Navbar on Scroll Using Bootstrap
Searching for a solution to animate or shrink a navbar when scrolling can often lead to outdated information, especially those pertaining to Bootstrap 3. This article focuses on current solutions for Bootstrap 4 and 5.
Bootstrap 5
Bootstrap 5 retains the sticky-top class for creating a static-to-fixed navbar effect on scroll. Alternatively, you can utilize JavaScript IntersectionObserver to monitor a "trigger" element and apply a CSS class to the navbar when the trigger becomes visible. This class can then contain the necessary CSS to adjust the navbar's appearance and position.
Bootstrap 4
Since Bootstrap 4 lacks the Affix component, you can use the sticky-top class to affix the navbar when it reaches the top. However, this method alone will not trigger a JavaScript event to indicate when the navbar is affix. As a result, you'll need JavaScript to manipulate the navbar's style once it becomes sticky. IntersectionObserver is a suitable option to detect when a trigger element above the navbar reaches the viewport and triggers the "sticky" state.
jQuery Alternatives
Besides using Bootstrap's built-in functionality, you can also employ jQuery plugins like ScrollPos-Styler or write your own jQuery script to control the navbar's style on scroll. One approach is to define a fixed-top navbar with data-toggle="affix" and use jQuery to watch the scroll position and conditionally toggle the .affix class.
Additional Resources
The above is the detailed content of How to Animate or Shrink a Bootstrap Navbar on Scroll?. For more information, please follow other related articles on the PHP Chinese website!