Search code examples
htmlcsstwitter-bootstrapbootstrap-4styles

Navbar on top of background image bootstrap 4.0


I am trying to have my navbar be on top of my background imagein bootstrap 4.0. I can do this via negative margin top on the background image but that is not easy to work with if i make changes to my site.

HTML:

<div class="masthead">
    <nav>
        <img src="https://test.io/wp-content/uploads/2019/02/testIO-logo-rgb-2.png" class="site-logo" />
    </nav>
</div>
<div class="container-fluid hero"> </div>

CSS:

.hero {
  height: 600px;
  background-image: url(https://s17736.pcdn.co/wp-content/uploads/2019/03/asoggetti-318284-unsplash-1024x684.jpg);
  background-position: center center;
  width: 100%;
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
  margin-bottom: 15px;
}

nav {
  background: transparent;
  background-attachment: fixed;
  background-position: auto,center;
}

.site-logo {
  height: 64px;
}

JSFiddle


Solution

  • Use display:relative; to parent div and display:absolute; and top:0; to child(nav).

    Whenever you need the logo(which is common use case) to put on the top without using the negative values then use, positions for parent and child, if there are no parent then the body will be considered as parent and it will positioned absolute to body.

    You don't have to use negative value since the absolute will fit-in the image as expected for all instances.

    fiddle to playaround.

    .hero {
      height: 600px;
      background-image: url(https://s17736.pcdn.co/wp-content/uploads/2019/03/asoggetti-318284-unsplash-1024x684.jpg);
      background-position: center center;
      width: 100%;
      padding-right: 15px;
      padding-left: 15px;
      margin-right: auto;
      margin-left: auto;
      margin-bottom: 15px;
    }
    
    .masthead {
      display: relative;
    }
    
    nav {
      background: transparent;
      background-attachment: fixed;
      background-position: auto, center;
      position: absolute;
      top: 0;
    }
    
    .site-logo {
      height: 64px;
    }
    <div class="masthead">
      <nav>
        <img src="https://test.io/wp-content/uploads/2019/02/testIO-logo-rgb-2.png" class="site-logo" />
      </nav>
    </div>
    <div class="container-fluid hero"> </div>