OneMoreQuestion OneMoreQuestion - 1 year ago 135
CSS Question

How to fix Bootstrap navbar fixed top padding on browser resize

I have a

navigation bar that always stays on top of the page. I have given the
a padding of 70 px and this works well with it.

The problem is if I resize the browser, then the nav-bar is no longer nice and neat with a fixed height. Instead it wraps all the items in it, the height of the nav bar becomes more than 70 px and covers parts of the page.

To fix this, I tried using JQuery to check the height of the nav bar and give body more padding, I put this in

if ($(".navbar.navbar-inverse.navbar-fixed-top").height() > 100) {
$("html, body").css("padding-top", "150px");

However, this solution does not work because the browser is not reloaded when its size shrinks so therefore this check does not happen dynamically. So how do I fix this?

Answer Source

You can use the window resize event listener here. Something like this:

$( window ).resize(function() {
  if ($(".navbar.navbar-inverse.navbar-fixed-top").height() > 100) {
    $("html, body").css("padding-top", "150px");

Additionally you could also go the Bootstrap way and collapse and expand the Navbar into a button, depending on screen resolution. The above approach is slightly less than ideal IMO