Search code examples
cssbackground-imagelinear-gradients

Can I position and size a linear-gradient within the background?


I have been wrestling with a layered CSS background today. I am trying to have three layers (from foreground to background):

  • an image
  • a black bar (emulated with a linear-gradient
  • a gradient overlay

This is my CSS for the element:

  width: 100%;
  height: 100%;
  background-image: linear-gradient(to right, #00000000 0%, #00000000 15%, #000000ff calc(100% - 40rem)), linear-gradient(to right, #000000ff 0%, #000000ff 100%),  url("../assets/images/bg-1080-1920.png");
  background-size: cover, 40rem 4rem, auto;
  background-position: top left, 0rem 3rem, top left;

For some reason, the black bar I am trying to insert takes over the whole screen even though I have set background-position and background-size properties. After looking at MDN, I believe I have followed all of the rules. It does indicate that it may be a browser issue, but adding -webkit to the property name didn't help either (I am using a Chromium browser while I code).

MDN doesn't mention gradients on the background-position page and it still takes over the screen even if I remove that property. I have also tried entering sizes in px to see if it was an issue using the rem unit. Both to no avail.

Is there something obviously wrong with the property values? Or am I crazy.


Solution

  • Never forget background-repeat

    html {
      min-height: 100%;
      background-image: 
        linear-gradient(to right, #00000000 0%, #00000000 15%, #000000ff calc(100% - 40rem)), 
        linear-gradient(to right, #000000ff 0%, #000000ff 100%), 
        url("https://picsum.photos/id/1069/800/800");
      background-size: cover, 40rem 4rem, auto;
      background-position: top left, 0rem 3rem, top left;
      background-repeat:no-repeat; /* this is important !! */
    }