Trouble with multiple data-types in background-image CSS property

While exploring the How CSS is structured module I ran into trouble using both linear-gradient and url data-types for a background-image property.

When I copy the code from the background-image reference page then both data-types render as expected. Writing the code from scratch, however, with different rgba() values renders only the linear-gradient.

This happens in both Firefox and Chromium.

index.html:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <title>My CSS experiments</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body> 
    <div class="lizard-box"></div>
    <div class="mdn-box"></div>
    <div class="test-box"></div>
  </body>
</html>

styles.css:

/* Lizard image only - renders as expected */

.lizard-box {
  background-image: url(lizard.png);
  height: 400px;
  width: 400px;
}

/* MDN example code - renders as expected */

.mdn-box {
  background-image: 
    linear-gradient(rgba(0, 0, 255, 0.5), rgba(255, 255, 0, 0.5)),
    url(lizard.png);
  height: 400px;
  width: 400px;
}

/* Code from scratch - only the linear-gradient renders */

.test-box {
  background-image:
    linear-gradient(rgba(188, 143, 143, 1), rgba(143, 189, 189, 1)),
    url(lizard.png);
  height: 400px;
  width: 400px;
}

The lizard.png is from the MDN example.

What am I missing here?

Hi @jlbuckner!

The problem is that when you use multiple background images, images earlier in the list appear on top of images later in the list (which seems counter-intuitive to me, but hey, that’d the way it is).

This example works because the gradient is on top of the image, but the gradient is semi-transparent so the image shows through:

.mdn-box {
  background-image:
    linear-gradient(rgba(0, 0, 255, 0.5), rgba(255, 255, 0, 0.5)),
    url(lizard.png);
  height: 400px;
  width: 400px;
}

This one doesn’t work because your colors have an opacity of 1, so the image doesn’t show through at all:

.test-box {
  background-image:
    linear-gradient(rgba(188, 143, 143, 1), rgba(143, 189, 189, 1)),
    url(lizard.png);
  height: 400px;
  width: 400px;
}

If you swap the order of the images in the property value, the image will appear on top of the gradient:

.test-box {
  background-image:
    url(lizard.png),
    linear-gradient(rgba(188, 143, 143, 1), rgba(143, 189, 189, 1));
  height: 400px;
  width: 400px;
}
1 Like

Thanks @chrismills for the reply!

I understood context layering but somehow didn’t try switching the linear-gradient and url() while troubleshooting. :grimacing:

The biggest issue I missed was the rgba() transparency. Will read up on that.