Can I fade a background image into the background color?

Viewed 3374

I want a website to have a background color, and a background image that scales with the width, and keeps the aspect ratio. So far pretty easy:

body {
    background-attachment:fixed;
    background-color:#ff9999;
    background-image:url(https://i.redd.it/x7hdjnmupu901.jpg); // random image from google search
    background-position:top center;
    background-repeat:no-repeat;
    background-size:100% auto;
}

Now, is it possible with CSS to have the background image to the bottom side 'fade into' the background color? As in, have the bottom 50 pixels of the background image slowly lose alpha value, so it smoothly goes into the background color?

Here is a JSFiddle, if someone wants to see this / play around with it: http://jsfiddle.net/wkz1t2b3/5/

2 Answers

You could use linear-gradient to apply a second background-image, which is a gradient of your background color from 0 opacity to 100% opacity.

You can edit the 75% in the below linear-gradient to change the point at which the fade begins, and the 100% to adjust the point at which the background-color becomes fully visible.

body {
    background-attachment:fixed;
    background-color:#ff9999;
    background-image: linear-gradient(to bottom, rgba(255,153,153,0) 0%,rgba(255,153,153,0) 75%,rgba(255,153,153,1) 100%), url(https://i.redd.it/x7hdjnmupu901.jpg);
    background-position:top center;
    background-repeat:no-repeat;
    background-size:100% auto;
}

I'm afraid, if you want the fadding be attached to the background image in any screen size, you will need to add some extra elements, and be tricky with the CSS

But it still behaves as a background ...

Test screen resizings in : http://jsfiddle.net/wkz1t2b3/77/

body{ 
  margin:0px;
  background-color:#ff9999;
  color:white;
}

#background{
    width:100%;
    position:fixed;
    z-index:-1
}

#background img{width:100%;}

/* the body fade becomes visible only when the image is bigger than the viewport */
body::after{
    background-image:  linear-gradient(to bottom, transparent, #ff9999);
    content:'';
    display:block;
    height:50px;
    bottom:0px;
    position:fixed;
    width:100%;
    z-index:-1;
}

#background::after{
    background-image:  linear-gradient(to bottom, transparent, #ff9999);
    content:'';
    display:block;
    height:50px;
    bottom:0px;
    position:absolute;
    width:100%;
}
<div id="background">
  <img src="https://i.redd.it/x7hdjnmupu901.jpg">
</div>


It behaves as a background

Related