Search code examples
htmlcsstransparency

<div> Background image transparent but NOT text


I am trying to create a <div> that has a slow panning transparent background, as part of an HTML module in opencart. It being a module, styling has to be self contained.

What I have so far:

<style>
@keyframes backgroundScroll {
0% { background-position: 50% 50%; }
33% { background-position: 1% 50%; }
40% { background-position: 1% 50%; }
66% { background-position: 99% 50%; }
75% { background-position: 99% 50%; }
100% { background-position: 50% 50%; }}
/* added pauses to each edge of the image */

#mtn-scroll {
width: 800px;
height: 100%;
background: url(coolpanoramapicture.jpg) no-repeat; opacity:0.1;
background-size: 250%;
background-position: 50% 50%;
animation: backgroundScroll 60s ease-in-out 1s infinite; }
</style>

<div id="mtn-scroll">
  <div>
  Content text goes here!
  </div>
</div>

What I want is for opacity to NOT affect the text as well. Ive heard the bell ring about using ::before, but I have no idea where the hammer hangs. Was I onto something?

Does anyone know how to make ONLY the background image go transparent, without having to resort to finagling with a transparent PNG file?


Solution

  • You were on the right track with the ::before pseudo-element. Here's how to implement it:

    html,
    body {
      height: 100%;
    }
    
    #mtn-scroll {
      width: 800px;
      height: 100%;
      position: relative;
    }
    
    #mtn-scroll::before {
      background: url('https://i.imgur.com/4HLnakJ.jpg') no-repeat;
      opacity: 0.1;
      background-size: 250%;
      background-position: 50% 50%;
      animation: backgroundScroll 60s ease-in-out 1s infinite;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 0;
      content: '';
    }
    
    #mtn-scroll div {
      position: relative;
    }
    
    @keyframes backgroundScroll {
      0% {
        background-position: 50% 50%;
      }
      33% {
        background-position: 1% 50%;
      }
      40% {
        background-position: 1% 50%;
      }
      66% {
        background-position: 99% 50%;
      }
      75% {
        background-position: 99% 50%;
      }
      100% {
        background-position: 50% 50%;
      }
    }
    <div id="mtn-scroll">
      <div>
        Content text goes here!
      </div>
    </div>