Search code examples
htmlcssbackground-imagebackground-color

apply gradient on background-color


My background image is supposed to cover the whole background of my website.

Here the body-selector in the css file:

body {
    background-image: url(https://img.4plebs.org/boards/tv/image/1432/79/1432798812366.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    background-color: black;
}

In some weird screen-sizes the picture doesn't cover the screen properly and due to the no-repeat option the "underflow" appears white.

I therefore added the background-color: black in my body selector which works as a perfect "fall-back option". The background not covered by the image appears black now.

Now I'd like to make the transition between background-color and background-image smother by replacing the simple "black" with a gradient. But I didn't find a solution.

How I'd like it to be (not working):

body { 
    ...
    */apparently not a valid option for background-colour:*/
    background-color: linear-gradient(to right, rgb(1, 3, 0), rgb(26, 31, 38));
}

Solution

  • If you change your html code and add the background to a container instead of the body then use pseudo classes div::after you can do that.

    Check this code:

    body {
      margin: 0;
      padding: 0;
      background: black;
    }
    
    .main--container {
      background-image: url(https://img.4plebs.org/boards/tv/image/1432/79/1432798812366.jpg);
      background-size: cover;
      background-repeat: no-repeat;
      background-position: center;
      background-color: black;
      height: 90vh;
      width: 100%;
      margin: 0;
      padding: 0;
      position: relative;
    }
    
    .main--container::after {
      display: block;
      position: absolute;
      background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.0), rgba(0, 0, 0, 1));
      bottom: 0px;
      height: 140px;
      width: 100%;
      content: '';
    }
    <body>
      <div class="main--container">
      </div>
    </body>