Search code examples
htmlcsscss-position

Overlay effect without position:fixed;


I want to have a background-image with some overlay effect.

see: https://jsbin.com/giqagidufe/edit?html,css,output

The overlay effect should always be full screen size - also when resizing. I first did that using:

html, body { min-height: 100%; }

// Background Image
body {
    position: relative;
    background-image: url("/_Resources/Static/Packages/VMP.Website/Images/Header/header_full.jpg");
    background-position: top center;
    background-repeat: no-repeat;
    margin: 0px;
    background-color: black !important;
}

// Colored overlay of Background Image
body::before {
    position:absolute;
    content: '';
    background-color: rgba(44, 62, 80, 0.7);
    min-width: 100%;
    height: 100%;
    z-index: -10; 
}

so I used position:absolute; but that has the problem of not fully cover the whole screen. I thend used position:fixed; which solves the problem.

but that forces the browser to rerender the whole thing on each scroll, so it's not the best option.

Are there any other option I could do that? One which is more performant?


Solution

  • If we're on the same page, this is what you're looking for. Please let me know if this solves your problem.

    You should place both elements (image and overlay) as absolute. You can play with the last param of the RGBA property of class overlay to set the opacity.

    It's fully responsive, which adheres to your question. Here's a fiddle

    HTML

      <head>
        <link rel="stylesheet" href="style.css">
        <script src="script.js"></script>
      </head>
    
      <body>
        <div class="overlay"></div>
      </body>
    
    </html>
    

    CSS

    html, body { min-height: 100%; }
    body {
        padding: 0;
        border: 0;
        width:100%; 
        height:100%; 
        margin: auto;
        position: absolute;
        top: 0; left: 0; bottom: 0; right: 0;
        background-image: url("http://wallpapercave.com/wp/8fWGVfB.jpg");
        background-position: top center;
        background-repeat: no-repeat;
    }
    .overlay{
        width:100%; 
        min-height:100%; 
        background-color: rgba(0,0,0,0.4);
        position: absolute;
    }