I have two Navbars with fixed-top
classes displayed one below the other - second one having top: *height of first navbar*
css added to it.
Whenever user scrolls down, the height of the first navbar shrinks by removing extra pt
pb
bootstrap padding classes using modified code from this question's answer.
Since both Navbars are fixed, when the shrinkage of the first one occurs, there is a gap produced between the two navbars.
My solution to this was very drastic - I used javascript-detect-element-resize library to detect the resize of the first navbar and change the top
css property of the second Navbar according to the height of the first Navbar.
Given that this is rather CPU consuming task since I have transition
css property set for the first Navbar padding attribute transition:padding 0.2s ease;
and also during the transition there is a visible 1-2 pixel gap still seen between the navbars up 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 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>
Relevant CSS:
#second {
top: 80px; //customized (first) Navbar's 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;
}
Relevant JS:
if ($('#first').scrollTop() > 80){
$('#first').addClass("no-padding");
}
else {
$('#first').removeClass("no-padding");
}
On Codeply: https://www.codeply.com/go/GAI3gEtta2
I think you should wrap both navbars in a single DIV, and make that the data-toggle="affix"
element. This way you only make the outer DIV fixed, and the second navbar will naturally follow the height of the 2nd since both are static position.
https://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 the CSS to apply the padding animation to the top navbar instead of the 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;
}