responsive fixed-top navbar when expanded fills up

2019-08-18 16:15发布

问题:

I have created a fixed-top bootstrap 4 navbar that is expanded on large screens, and collapsed on the others. I have also added padding-top to the <body> to prevent the navbar from overlapping the main body content.

However, on smaller screens when the collapsed navbar is expanded using the hamburger button, it expands and fills the screen. Some of the nav-links then become hidden (i.e. outside the display). Moreover,scrolling does not scroll the navbar, but only the main body content which is beneath the navbar.

Is it possible to compress the navbar to not take up more than the screen size? Or, how do I enable a scrollable navbar?

Added pictures below to show the issue.

Here is a snap in mobile view without expanding the navbar:

And here is the snap to illustrate the problem that the navbar takes up the whole viewport, and that there are still links but "outside" the display:

Here is JSFiddle if needed: https://jsfiddle.net/suhaib47/ef37ht06/6/


Edit:

After using the answer provided by @Zim, I now face a different problem. In the desktop screen, the navbar is displayed properly. However, when I click on the nav-items/nav-links which pop open a dropdown list, the dropdown list stays within the navbar and there is a scroll bar for scrolling the navbar. How do I make the dropdown menu to show over the navbar content, while at the same time it can be scrolled but only when the navbar is collapsed.

I've included a picture to show what I mean:

The scrollbar seen in the picture is for the navbar.

回答1:

Set a max-height on the .navbar-collapse that's equal to viewport height minus the body top padding...

body {
  overflow: hidden;
}

.fixed-top .navbar-collapse {
  max-height: calc(100vh - 4.5em);
  overflow-y: auto;
}

https://www.codeply.com/go/1KXwX3I1Mh