Search code examples
htmlcssbackground-image

How do I position a nav menu within a header beneath the background image?


As of now, I have the code bellow after trying several different combinations. I am trying to get the nav menu underneath the background image but still within the header element.

I have tried several different styles, but have found that this is closest to what I am looking for. The code is probably messy as this is my first project and I am just learning, but I cannot seem to find the answer anywhere. I am hoping to put the menu beneath the background image.

Sample Dentistry Page

header {
  background-image: url(https://picsum.photos/1536/1354);
  height: 250px;
  background-repeat: no-repeat;
  background-position: center;
  margin: 1em;
  padding: 1em;
  grid-area: header;
}

nav ul {
  margin: 0px;
  padding: 0px;
  list-style-type: none;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}

nav ul li a {
  display: block;
  border: 1px solid;
  border-radius: .5em;
  padding: .25em;
  margin: .5em;
}
<header id="banner">
  <h1>Dentistry Page</h1>
  <nav>
    <ul>
      <li><a href="index.html">Home</a></li>
      <li><a href="Services/services.html">Services</a></li>
      <li><a href="About/about.html">About</a></li>
      <li><a href="Contact/contact.html">Contact</a></li>
    </ul>
  </nav>
</header>


Solution

  • If you have an element inside of a container such as a div or header, and you apply a background to that container, you can't move that element underneath the background as long as it's in that container. If you want to keep the navbar inside the header, you'll have to create a div within the header that you exclusively apply the background to, and then any content you have after that div will be displayed underneath.

      <header id="banner">
        <div id='background'>
          <h1>Dentistry Page</h1>
        </div>
        <nav>
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="Services/services.html">Services</a></li>
                <li><a href="About/about.html">About</a></li>
                <li><a href="Contact/contact.html">Contact</a></li>
            </ul>
        </nav>
      </header>
    
    
    
    
    
    #background {
        background-image: url(Images/Homepage-Feature-Image-Mobile.jpg);
        height: 250px;
        background-repeat: no-repeat;
        background-position: center;
        margin: 1em;
        padding: 1em;
        grid-area: header;
    }
    
    nav ul {
        margin: 0px;
        padding: 0px;
        list-style-type: none;
        display: flex;
        justify-content: center;
        align-items: flex-end;
    }
    
    nav ul li a {
        display: block;
        border: 1px solid;
        border-radius: .5em;
        padding: .25em;
        margin: .5em;
    }