Search code examples
htmlcssbackground-imageopacity

How to change only the background image opacity?


I am trying to change the opacity of my background image to make it match the website. The problem is that the opacity: 0.5; change everything within the element. So not only the background image change but also the text and every other element in the section. How am i supposed to change only the color of the image? Here is my code:

section {
   background-image: url(../IMG/Photo_NR1.jpg);
   padding: 15px;
   width: 100%;
   height: 700px;
}

I have done some research but i couldn't find anything. I tried to have all my elements out of the <section> tag but then i was forced to change the position of the elements again. Thanks for your time :)


Solution

  • You could also do this by a pseudo element. Something like this:

    section {
       position: relative;
       padding: 15px;
       width: 100%;
       height: 700px;
    }
    
    section::before {
      content: "";
      position: absolute;
      top: 0; 
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      opacity: .5; 
      background-image: url(../IMG/Photo_NR1.jpg);
    }
    

    So you do not need an image tag and you separating the design from content.