Search code examples
htmlcss

Why the background image in my code is getting disappeared as soon as I apply absolute position to it?


I am trying to clone netflix UI but getting error while applying the background image with its position as absolute with top:0. I have attached both html and css codes. Please help me out in identifying the issue.

I have already given relative position to parent-container.

*{
    margin: 0;
    padding: 0;
}

.parent-container{
    position: relative;
    height: 120vh;
    width: auto;
}

/* header nav .logo{
    position: absolute;
    top: 0;
} */

.frontPage{
    background-image: url('https://picsum.photos/seed/picsum/200/300');
    background-position: center center;
    background-repeat: no-repeat;
    background-size: max(1500px,100%);
    filter: brightness(0.5);
    width: auto;
    height: 110vh;
    position: absolute;
    top: 0;
    left: 0;

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clone - Netflix</title>
    <link rel="stylesheet" href="stylesheet.css">
</head>
<body>
    <div class="parent-container">

        <header>
            <nav>
                <div class="logo">
                    <img src="https://picsum.photos/30/30" alt="Netflix icon"> 
                </div>
            </nav>
        </header>

        <div class="frontPage">

        </div>


    </div>
    
    <footer>

    </footer>
</body>
</html>


Solution

  • The problem is that you are setting width: auto. When the div element has no position attribute defined, it will take up 100% of its container due to its default of block display styling. However, when you add position: absolute, it no longer has a basis for its width and the width will shrink to 0.

    You can see in this snippet that the red rectangle shows, while the blue cannot be seen.

    <div style="width: 400px; height: 100vh;">
      <div style="height: 100px; background: red;"></div>
      <div style="height: 50px; background: blue; position: absolute; top: 0; left: 0;"></div>
    </div>