Bootstrap 4 Multiple Fixed Navbars with Animated Compression

I have two Navbars with fixed-top classes displayed one below the other - the second with the addition of top: *height of first navbar* css.

Whenever a user scrolls down, the height of the first navigation bar decreases, removing the extra pt pb boot classes of the boot, using the modified code from this answer to the question.

Since both Navbars are fixed when the first one shrinks, a gap arises between the two navigators.

My solution for this was very decisive - I used the javascript-detect-element-resize library to detect the resizing of the first navigation bar and changing the top css property of the second Navbar to match the height of the first Navbar.

Given that this is a rather expensive processor task, since I have the transition css property set for the first padbar attribute padding transition:padding 0.2s ease; , and also during the transition there is a visible gap of 1-2 pixels, which is still observed between navbars until the end of the transition.

Is there a better way to “attach” the second Navbar to the first so that it follows whenever the first Navbar changes its height?

Relevant Code:

 <nav class="navbar navbar-light bg-faded fixed-top pb-5 pt-5" id="first"> <a class="navbar-brand">First</a> </nav> <nav class="navbar navbar-light bg-faded fixed-top" id="second"> <a class="navbar-brand">second</a> </nav> 

Matching CSS:

 #second { top: 80px; //customized (first) Navbar height } #first { -webkit-transition:padding 0.2s ease; -moz-transition:padding 0.2s ease; -o-transition:padding 0.2s ease; transition:padding 0.2s ease; } .no-padding { padding: 0 !important; } 

Corresponding JS:

 if ($('#first').scrollTop() > 80){ $('#first').addClass("no-padding"); } else { $('#first').removeClass("no-padding"); } 

On Codeply: https://www.codeply.com/go/GAI3gEtta2

+1
css twitter-bootstrap twitter-bootstrap-4 bootstrap-4
source share
1 answer

I think you should wrap both nubbars in one DIV and make this element data-toggle="affix" . That way, you only capture the external DIV, and the second navigator will naturally follow the height of the 2nd, as both are static.

https://www.codeply.com/go/DpHESPqZsx

 <div class="fixed-top" data-toggle="affix"> <div class="navbar navbar-dark bg-dark navbar-expand-sm py-5" id="first"> ... </div> <div class="navbar navbar-light bg-light navbar-expand-sm" id="second"> ... </div> </div> 

Adjust CSS to apply add-on animation to the top navigation bar instead of an affix element:

 .fixed-top #first { -webkit-transition:padding 0.2s ease; -moz-transition:padding 0.2s ease; -o-transition:padding 0.2s ease; transition:padding 0.2s ease; } .affix #first { padding-top: 0.2em !important; padding-bottom: 0.2em !important; -webkit-transition:padding 0.2s linear; -moz-transition:padding 0.2s linear; -o-transition:padding 0.2s linear; transition:padding 0.2s linear; } 
+1
source share

All Articles