Search code examples
cssbackgroundbootstrap-4zooming

CSS - Zoom in background only (no overlay text)


I'm trying to do the background image zoom in effect. The code below represents one clickable element with an image background. The problem I have is that it zooms in everything in that div including child divs. I'd just want the background image to zoom in (leave the overlay text intact)

<a class="outer-tile tile-text" href="#">
    <div class="inner-tile d-flex flex-column align-items-start" style="background-image: url('https://picsum.photos/200/300')">
      <div class="mb-auto p-2">
        <span class="b-dark p-1">MyTag</span>
      </div>
      <div class="b-dark w-100 p-2">
        <h3>My Title</h3>
        <p>This is the content</p>
      </div>
    </div>
  </a>


.outer-tile {
    overflow: hidden;
    height: 400px;
}

.inner-tile {
    height: 100%;
    width: 100%;
    background-size: cover;
    background-position: center;
    transition: all 0.5s ease;
}

.inner-tile:hover {
    transform: scale(1.2);
}

Here's a codepen:

How would I make only the background to zoom in without zooming in on text?


Solution

  • You can place the background image on an element that is a sibling to the text elements, not a parent. Then use positioning and z-index to place it behind them:

    .outer-tile {
        overflow: hidden;
        height: 400px;
      position:relative;
    }
    
    .tile-underlay {
        position:absolute;
        top:0;
        right:0;
        bottom:0;
        left:0;
        z-index:-1;
        background-size: cover;
        background-position: center;
        transition: all 0.5s ease;
    }
    
    .outer-tile:hover .tile-underlay {
        transform: scale(1.2);
    }
    
      <a class="outer-tile tile-text" href="#">
          <div class="tile-underlay d-flex flex-column align-items-start" style="background-image: url('https://picsum.photos/200/300')"></div>
          <div class="mb-auto p-2">
            <span class="b-dark p-1">MyTag</span>
          </div>
          <div class="b-dark w-100 p-2">
            <h3>My Title</h3>
            <p>This is the content</p>
          </div>
    
      </a>
    

    https://codepen.io/anon/pen/NLyYKY