ChatGPT解决这个技术问题 Extra ChatGPT

top nav bar blocking top content of the page

I have this Twitter Bootstrap code

  <div class='navbar navbar-fixed-top'>
    <div class='navbar-inner'>
      <div class='container'>
        <a class='btn btn-navbar' data-target='.nav-collapse' data-toggle='collapse'>
          <span class='icon-bar'></span>
          <span class='icon-bar'></span>
          <span class='icon-bar'></span>
        </a>
        <div class='nav-collapse'>
          <ul class='nav'>
            <li class='active'>
              <a href='some_url'>My Home</a>
            </li>
            <li>
              <a href='some_url'>Option 1 </a>
            </li>
            <li>
              <a href='some_url'>Another option</a>
            </li>
            <li>
              <a href='some_url'>Another option</a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>

But when I am viewing the beginning of the page, the nav bar is blocking some of the content that is near the top of the page. Any idea for how to make it push down the rest of the content lower when the top of the page is viewed so that the content isn't blocked by the nav bar?

@user2428107 That question was posted later.

K
KyleMit

Adding a padding like that is not enough if you're using responsive bootstrap. In this case when you resize your window you'll get a gap between top of the page and navbar. A proper solution looks like this:

body {
  padding-top: 60px;
}
@media (max-width: 979px) {
  body {
    padding-top: 0px;
  }
}

Perfect. This should really be integrated into bootstrap somehow. You should fork and submit a pull request.
Good solution, but there is still something not solved. Take a look to this question I have just made and see if anyone can give a hand on it. stackoverflow.com/questions/12763707/…
Even more succinctly: @media (min-width: 981px) { body { padding-top: 60px; } }
@Ted for me it has to be min-width: 980px ;-)
@white_gecko lol. Yep. That 980 wanted to be just a little extra special unique ;-)
Z
Zim

Add to your CSS:

body { 
    padding-top: 65px; 
}

From the Bootstrap docs:

The fixed navbar will overlay your other content, unless you add padding to the top of the body.


See additional answer below by @Spajus for how to code this for responsive Bootstrap
Definitely roll with the other answer with a little more succinctness with @media (min-width: 980px) { body { padding-top: 60px; } }
While the other answers do address this more eloquently, this is the official answer as noted in the Bootstrap documentation for Fixed Navbar link
How will that work if the user has a narrower screen or simply resizes the window? The topmost contents will be blocked again by the expanded nav bar section.
j
jojo

For bootstrap 3, the class navbar-static-top instead of navbar-fixed-top prevents this issue, unless you need the navbar to always be visible.


This works however might leave some space above the navbar. You may need to modify site.css and remove padding-top 80px from body.
I tried everything and this is the only answer that worked. Because this is the most general solution and doesn't depend on screen size, this should be the correct answer.
This fixed the problem. Why does this work instead of navbar-fixed-top?
It did not worked for bootstap 3.3.4. I see fixed nav example at bootstrap site getbootstrap.com/examples/navbar-fixed-top, It uses padding-top
while this works, it makes the navbar static and not fixed. that means that when you scroll down the navbar will disappear... at least for me that's not good.
c
catsky

a much more handy solution for your reference, it works perfect in all of my projects:

change your first 'div' from

<div class='navbar navbar-fixed-top'>

to

<div class="navbar navbar-default navbar-static-top">

The static navbar disappears when scrolling.
Re: @DanielC.Sobral response - you could switch it out for the fixed one in js if it scrolls off the top
A
Aram Paronikyan

I am using jQuery to solve this problem. This is the snippet for BS 3.0.0:

$(window).resize(function () { 
    $('body').css('padding-top', parseInt($('#main-navbar').css("height"))+10);
});

$(window).load(function () { 
    $('body').css('padding-top', parseInt($('#main-navbar').css("height"))+10);        
});

I was using a image over the navbar and having real problems with the content being hidden. This worked perfectly! Thanks!
thank you so much for your solution. this answer worked like a charm for me :) I'd like to add one thing. When you load the page, the body is set to the top before it adjusts itself automatically because jquery doesnt run instantly. To make it smoother, I added this in CSS body{ padding-top: //initial height of my navbar; } This helps in smooth transition! Thank you again!
Thanks for inspiring a programatic solution! I have a great working implementation now in GWT with nice encapsulated well structured code... thanks to a lack of Javascript ;-)
P
PiersB

In my project derived from the MVC 5 tutorial I found that changing the body padding had no effect. The following worked for me:

@media screen and (min-width:768px) and (max-width:991px) {
    body {
        margin-top:100px;
    }
}
@media screen and (min-width:992px) and (max-width:1199px) {
    body {
        margin-top:50px;
    }
}

It resolves the cases where the navbar folds into 2 or 3 lines. This can be inserted into bootstrap.css anywhere after the lines body { margin: 0; }


After studying all answers, this seems like the best solution. (navbar-static-top makes it disappear when scrolling, & the dummy navbar doesn't take into account how the real navbar menu might wrap.) I found that bootstrap has four hardcoded width cases: <768 pixels, 768-991, 992-1199, and >1199. See how your menu behaves for those 4 cases. For non-admin users of my website, I only needed the 100 pixels for the 768-991 case & that was sufficient. Was put into site.css. Or, I noticed that our menu is wider for admin users and wraps more easily. So we put conditional style code in _Layout.cshtml
using margin-top instead of padding-top moves down a content beneath of navbar. It's true that padding-top applied to body doesn't work in MVC but it seems it works when applied to a body container.
J
Jason Butler

I've had good success with creating a dummy non-fixed nav bar right before my real fixed nav bar.

<nav class="navbar navbar-default"></nav> <!-- Dummy nav bar -->
<nav class="navbar navbar-default navbar-fixed-top"> <!-- Real nav bar -->
    <!-- Nav bar details -->
</nav>

The spacing works out great on all screen sizes.


I thought this was the answer at first and was all set to give an upvote. But then I realized it doesn't work when the size gets narrow enough to have it stack the menu buttons. :-(
You're right it won't work with menu stacking without additional code. I usually just keep my menu bars at one line of height and turn the menu options into a hamburger button when the size narrows.
i have no idea why, but this works. can u elaborate on why it works ?
Great idea! as it's useful when some pages have a navbar and some not, as it's not possible to differentiate froms css file.
This is definitely the way to go. It works on all devices, even when the navbar breaks into two lines. +1
Y
Yihui Xie

The bootstrap v4 starter template css uses:

body {
  padding-top: 5rem;
}

N
Nabil Kadimi

As seen on this example from Twitter, add this before the line that includes the responsive styles declarations:

<style> 
    body {
        padding-top: 60px;
    }
</style>

Like so:

<link href="Z/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
    body {
        padding-top: 60px;
    }
</style>
<link href="Z/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />

A
Abhilash

using percentage is much better solution than pixels.

body {
  padding-top: 10%; //This works regardless of display size.
}

If needed you can still be explicit by adding different breakpoints as mentioned in another answer by @spajus


E
Eldiyar Talantbek

with navbar navbar-default everything works fine, but if you are using navbar-fixed-top you have to include custom style body { padding-top: 60px;} otherwise it will block content underneath.


This doesn't add any information that isn't already in other answers.
M
Michael Cole

Two problems will happen here:

Page load (content hidden) Internal links like this will scroll to the top, and be hidden by the navbar:

hello

World

Bootstrap 4 w/ internal page links

To fix 1), as Martijn Burger said above, the bootstrap v4 starter template css uses:

body {
  padding-top: 5rem;
}

To fix 2) check out this issue. This code mostly works (but not on 2nd click of same hash):

window.addEventListener("hashchange", function() { scrollBy(0, -70) })

This code animates A links with jQuery (not slim jQuery):

  // inline theme global code here
  $(document).ready(function() {
    var body = $('html,body'), NAVBAR_HEIGHT = 70;
    function smoothScrollingTo(target) {
      if($(target)) body.animate({scrollTop:$(target).offset().top - NAVBAR_HEIGHT}, 500);
    }
    $('a[href*=\\#]').on('click', function(event){
      event.preventDefault();
      smoothScrollingTo(this.hash);
    });
    $(document).ready(function(){
      smoothScrollingTo(location.hash);
    });
  })

b
boatcoder

The best solution I've found so far, that does not involve hard coding heights and breakpoints is to add an extra <nav... tag to the markup.

<nav class="navbar navbar-expand-md" aria-hidden="true">
    <a class="navbar-brand" href="#">Navbar</a>
</nav>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
    <a class="navbar-brand" href="#">Navbar</a>

By doing it this way the @media breakpoints are identical, the height is identical (provided your navbar-brand is the tallest object in the navbar but you can easily substitute another element in the non fixed-top navbar.

Where this fails is with screen readers which will now present 2 navbar-brand elements. This points at the need for a not-for-sr class to prevent that element from showing up for screen readers. However that class does not exist https://getbootstrap.com/docs/4.0/utilities/screenreaders/

I've tried to compensate for the screen reader issue with aria-hidden="true" but https://www.accessibility-developer-guide.com/examples/sensible-aria-usage/hidden/ seems to indicate this will probably not work when the screen reader is in focus mode which is of course the only time you actually need it to work...


U
Ultroman the Tacoman

EDIT: This solution is not viable for newer versions of Bootstrap, where the navbar-inverse and navbar-static-top classes are not available.

Using MVC 5, the way I fixed mine, was to simply add my own Site.css, loaded after the others, with the following line: body{padding: 0}

and I changed the code in the beginning of _Layout.cshtml, to be:

<body>
    <div class="navbar navbar-inverse navbar-static-top">
        <div class="container">
            @if (User.Identity.IsAuthenticated) {
                <div class="top-navbar">

navbar-static-top is not defined in Bootstrap4. Neither is navbar-inverse
I guess this answer is out-dated, then. I'll add a note to the answer.
a
adiga

you should add

#page {
  padding-top: 65px
}

to not destroy a sticky footer or something else


N
Nathaniel Ford
<div class='navbar' data-spy="affix" data-offset-top="0">

If your navbar is on the top of the page originally, set the value to 0. Otherwise, set the value for data-offset-topto the value of the content above your navbar.

Meanwhile, you need to modify the css as such:

.affix{
  width:100%;
  top:0;
  z-index: 10;
}

a
adiga

Add this:

.navbar {
  position: relative;
}

A
Afsan Abdulali Gujarati

You can use .stick-top which would do the same job of fixing the navbar to the top when scrolled without having to add any css padding

<div class="container-fluid mt-3">
  <nav class="navbar navbar-expand-sm bg-white navbar-light sticky-top pt-0">
    <a class="navbar-brand" href="/">
      <img src="/images/logo-full.png" alt="logo" width="150">
    </a>
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="/">Home</a>
      </li>
    </ul>
  </nav>
  <div class="row">
     .....
  </div>
</div>


c
cottonova

Add to your JS:

jQuery(document).ready(function($) {
  $("body").css({
    'padding-top': $(".navbar").outerHeight() + 'px'
  })
});

This will not work if the window is resized since your padding-top is only applied at document ready.
S
Shailesh Ladumor

you can set margin based on screen resolution

@media screen and (min-width:768px) and (max-width:991px) {
body {
    margin-top:100px;
}

@media screen and (min-width:992px) and (max-width:1199px) {
  body {
    margin-top:50px;
  }
}

body{
  padding-top: 10%;
}

#nav{
   position: fixed;
   background-color: #8b0000;
   width: 100%;
   top:0;
}

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now