Transparent Background Image with a Gradient

Keep in mind that a CSS gradient is actually an image value, not a color value as some might expect. Therefore, it corresponds to background-image specifically, and not background-color, or the entire background shorthand.

Essentially, what you’re really trying to do is layering two background images: a bitmap image over a gradient. To do this, you specify both of them in the same declaration, separating them using a comma. Specify the image first, followed by the gradient. If you specify a background color, that color will always be painted underneath the bottom-most image, which means a gradient will cover it just fine, and it will work even in the case of a fallback.

Because you’re including vendor prefixes, you will need to do this once for every prefix, once for prefixless, and once for fallback (without the gradient). To avoid having to repeat the other values, use the longhand properties1 instead of the background shorthand:

#mydiv .isawesome { 
    background-color: #B1B8BD;
    background-position: 0 0;
    background-repeat: no-repeat;

    /* Fallback */
    background-image: url('../images/sidebar_angle.png');

    /* CSS gradients */
    background-image: url('../images/sidebar_angle.png'), 
                      -moz-linear-gradient(top, #ADB2B6 0%, #ABAEB3 100%);
    background-image: url('../images/sidebar_angle.png'), 
                      -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ADB2B6), color-stop(100%, #ABAEB3));
    background-image: url('../images/sidebar_angle.png'), 
                      linear-gradient(to bottom, #ADB2B6, #ABAEB3);

    /* IE */
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ADB2B6", endColorstr="#ABAEB3", GradientType=0);
}

Unfortunately this doesn’t work correctly in IE as it uses filter for the gradient, which it always paints over the background.

To work around IE’s issue you can place the filter and the background image in separate elements. That would obviate the power of CSS3 multiple backgrounds, though, since you can just do layering for all browsers, but that’s a trade-off you’ll have to make. If you don’t need to support versions of IE that don’t implement standardized CSS gradients, you have nothing to worry about.


1 Technically, the background-position and background-repeat declarations apply to both layers here because the gaps are filled in by repeating the values instead of clamped, but since background-position is its initial value and background-repeat doesn’t matter for a gradient covering the entire element, it doesn’t matter too much. The details of how layered background declarations are handled can be found here.

Leave a Comment