Search code examples
cssbackground-imagegradienttransparentfade

CSS - Fade div into background image


Is there a way to achieve the following design with CSS?

transparent gradient example

It is basically a container with a background-image: url("...") and an inner div that is gradually faded into transparency at the bottom.

I know how to do a fade out with a mono color background using linear-gradient(transparent, white), but not with a background-image like in the example above. The content of the inner div could be anything, not just text.


Solution

  • Alright, I found the solution: mask-image: -webkit-gradient(...)

    Browser support is not optimal though...

    Example:

    body {
      background: url('https://images.unsplash.com/photo-1531315630201-bb15abeb1653?w=500') center no-repeat;
      background-size: cover;
    }
    
    div {
      width: 200px;
      height: 150px;
      overflow: hidden;
      background: cyan;
      -webkit-mask-image: -webkit-gradient(linear, center top, center bottom, 
    			color-stop(0.50,  rgba(0,0,0,1)),
    			color-stop(1.00,  rgba(0,0,0,0)));
      mask-image: -webkit-gradient(linear, center top, center bottom, 
    			color-stop(0.50,  rgba(0,0,0,1)),
    			color-stop(1.00,  rgba(0,0,0,0)));
    }
    <div>
      	Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>

    More info: https://css-tricks.com/clipping-masking-css/