Search code examples
htmlcssbackground-image

background image doesn't show up although has set the absolute and relative display for the tag


This is the html

</head>
<body>
    <header>
        <h2>Mountain Travel</h2>
        <nav>
            <li><a href="#">Tour</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
    </header>
    <section class="introduction">
        <div class="background-image" style="background-image: url(assets/image/main.jpg);" >

        </div>
        <div class="content-area">
            <h1>Mountain Travel</h1>
            <h3>Unmissable Adventure Tours Around The World</h3>
            <a href="#" class="btn">Contact Us Now</a>
    </div>
  </section>
</body>
</html>

This is the CSS:

.introduction.background-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-size: cover;
    z-index: -1;

}
.introduction{
    position:relative;
}

However, the image doesn't show up at all. I am sure that the url is correct. Could anyone help me with it?


Solution

  • So first you don't have a valid html structure (your nav tag was not close). Secondly the .background-image is a child of .introduction. So to access it in css you will need to use .introduction .background-image and not .introduction.background-image:

    .introduction .background-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-size: cover;
        z-index: -1;
    }
    
    .introduction{
        position:relative;
    }
    <header>
      <h2>Mountain Travel</h2>
      <nav>
        <ul>
          <li><a href="#">Tour</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </nav> <!-- Don't forget to close your nav tag-->
    </header>
    
    <section class="introduction">
      <div class="background-image" style="background-image: url(https://www.google.fr/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png);" ></div>
    
      <div class="content-area">
        <h1>Mountain Travel</h1>
        <h3>Unmissable Adventure Tours Around The World</h3>
        <a href="#" class="btn">Contact Us Now</a>
      </div>
    </section>

    I use in this example a reliable source (google logo) for your image path. So if in your example it's still not working maybe the source of the image is not the good one.

    As mentionned by @KoshVery please don't forget that a li need to be in a ul or ol html tag.