How do I combine a background-image and CSS3 gradient on the same element?

Ronald  picture Ronald · Mar 23, 2010 · Viewed 776.5k times · Source

How do I use CSS3 gradients for my background-color and then apply a background-image to apply some sort of light transparent texture?

Answer

Gidgidonihah picture Gidgidonihah · Mar 30, 2010

Multiple backgrounds!

body {
  background: #eb01a5;
  background-image: url("IMAGE_URL"); /* fallback */
  background-image: url("IMAGE_URL"), linear-gradient(#eb01a5, #d13531); /* W3C */
}

These 2 lines are the fallback for any browser that doesn't do gradients. See notes for stacking images only IE < 9 below.

  • Line 1 sets a flat background color.
  • Line 2 sets the background image fallback.

The final line sets a background image and gradient for browsers that can handle them.

  • Line 3 is for all relatively modern browsers.

Nearly all current browsers have support for multiple background images and css backgrounds. See http://caniuse.com/#feat=css-gradients for browser support. For a good post on why you don't need multiple browser prefixes, see http://codepen.io/thebabydino/full/pjxVWp/

Layer Stack

It should be noted that the first defined image will be topmost in the stack. In this case, the image is on TOP of the gradient.

For more information about background layering see http://www.w3.org/TR/css3-background/#layering.

Stacking images ONLY (no gradients in the declaration) For IE < 9

IE9 and up can stack images this same way. You could use this to create a gradient image for ie9, though personally, I wouldn't. However to be noted when using only images, ie < 9 will ignore the fallback statement and not show any image. This does not happen when a gradient is included. To use a single fallback image in this case I suggest using Paul Irish's wonderful Conditional HTML element along with your fallback code:

.lte9 #target{ background-image: url("IMAGE_URL"); }

Background position, sizing etc.

Other properties that would apply to a single image may also be comma separated. If only 1 value is supplied, that will be applied to all stacked images including the gradient. background-size: 40px; will constrain both the image and the gradient to 40px height and width. However using background-size: 40px, cover; will make the image 40px and the gradient will cover the element. To only apply a setting to one image, set the default for the other: background-position: 50%, 0 0; or for browsers that support it use initial: background-position: 50%, initial;

You may also use the background shorthand, however this removes the fallback color and image.

body{
    background: url("IMAGE_URL") no-repeat left top, linear-gradient(#eb01a5, #d13531);
}

The same applies to background-position, background-repeat, etc.