Search code examples
javascripthtmlcsslinear-gradients

Can I fade a background image into another background image in CSS (or even JS)?


Everything I've seen for this basically uses a background image with a linear gradient over the top of it, and that won't work for me:

I have 2 divs with background images that appear next to each other vertically, with, say, 50px of overlap. I would like to make the top 50px of the background image on the second div into a gradient so it fades in from transparent.

Here's the setup to start:

* {
  box-sizing: box-sizing:border-box;
}

div {
  width: 200px;
  height: 200px;
  padding: 10px;
  color: #fff;
}

.one {
  background-image: url('https://stevish.com/wpstevishcom/wp-content/uploads/2009/06/picture-0051-300x225.jpg');
}

.two {
  padding-top: 60px;
  margin-top: -50px;
  background-image: url('https://stevish.com/wpstevishcom/wp-content/uploads/2009/02/img_1530-large-225x300.jpg');
}
<div class="one">Unimportant content</div>
<div class="two">More unimportant content.</div>

And here's roughly what I want it to look like:

The two backgrounds fading into each other

I can't just upload a background image that fades one into the other because the content of the real divs is variable height, and the background needs to change only between the two divs.


Solution

  • mask can do it

    * {
      box-sizing: box-sizing:border-box;
    }
    
    div {
      width: 200px;
      height: 200px;
      padding: 10px;
      color: #fff;
    }
    
    .one {
      background-image: url('https://stevish.com/wpstevishcom/wp-content/uploads/2009/06/picture-0051-300x225.jpg');
    }
    
    .two {
      padding-top: 60px;
      margin-top: -50px;
      background-image: url('https://stevish.com/wpstevishcom/wp-content/uploads/2009/02/img_1530-large-225x300.jpg');
      -webkit-mask: linear-gradient(#0000, #000 50px);
    }
    <div class="one">Unimportant content</div>
    <div class="two">More unimportant content.</div>