Search code examples
cssbackground-imagetransparencytransparent

transparent background image without turning the content transparent


I have a background for the entire body of my page. Inside the body, I have a form that has another background image specifically for it. I want the background of that form to be slightly transparent so I could see the <body> background image.

What my code does:

makes the background and the content within the form both transparent

What I want to happen:

only make the background image slightly transparent and the text for content within it to remain at 100% opacity.


<style>
    #mainbody{
        background-image: url("/images/forest3.jpg");
        background-repeat: no-repeat;
        background-size: auto;
        background-size: 100% 100%;
        min-height: 700px;
        opacity: .5;
    }
    #mainbodyContent{
        opacity: 1;
    }
    body{
        background-repeat: no-repeat;
        background-size: cover;
        background-image: url("/images/trianglify/trianglifyBlue.png");
    }
</style>

<body>
    <div id="mainbody">
       <div id="mainbodyContent">
           ...some content
        </div>
    </div>
</body>

aditional info:

bootstrap 4.6


Solution

  • In such cases, use a pseudo-element by stretching it to the size of the block and setting the necessary styles.

    body {
      background-repeat: no-repeat;
      background-size: cover;
      background-image: url("https://i.sstatic.net/GEVAe.png");
    }
    
    #mainbody {
      position: relative;
      min-height: 700px;
      color: yellow;
    }
    
    #mainbody::before {
      content: "";
      position: absolute;
      top: 0; right: 0; bottom: 0; left: 0; z-index: -1;
      background-image: url("https://i.sstatic.net/57ffF.jpg");
      background-repeat: no-repeat;
      background-size: 100% 100%;
      opacity: 0.5;
    }
    
    #mainbodyContent {
      color: white;
    }
    <body>
      <div id="mainbody">
        ... some content in "#mainbody"
        <div id="mainbodyContent">
          ... some content in "#mainbodyContent"
        </div>
      </div>
    </body>