software

Cross-Platform CSS for Translucent DIVs

Had a need recently to make some translucent (semi-opaque) elements on a Web page. CSS3 supports an “alpha” channel, the “a” in rgba, to provide color opaqueness, but IE 7 and 8 do not support this attribute.  So, most web developers resort to using a translucent background-image.  However, there is a pure CSS way that is compatible with all modern browsers today (IE6 ignored, of course).  This takes advantage, though, of some CSS parsing bugs, so may not satisfy the CSS purists out there, but it works for me 🙂

Demo: solid background inner-box surrounded by a translucent box, overlaying a background-image.

The markup:

background-colorrgba(255,255,255,0.5); /* CSS3 */zoom:1/* required for the filters */
 *background-colortransparent ; /* IE7 only */
 background-colortransparent\9 ; /* IE8 only */
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#80FFFFFF, endColorstr=#80FFFFFF) ; /* IE8 */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#80FFFFFF, endColorstr=#80FFFFFF); /* IE7 */

To change the opaqueness of the div, edit both the alpha value in rgba() as well as the 1st hex value in the startColor and endColor filters. Convert to hex, of course: 0.7 alpha = B2 in hex (0.7 * 255); 0.5 = 80 hex, etc.

How this Works

background-color rgba() is the correct way to specify opaqueness, for all browsers that recognize CSS3. filter and -ms-filter are recognized by their respective IE browsers. The Gradient filter, with the same starting and end color, is used instead of the Alpha filter because the Alpha filter will also apply itself to children elements. background-color transparent is required for the MS filters to work. However, specifying it would override the rgba() value, thus messing with CSS3-compatible browsers, so we take advantage of a few CSS parsing hacks: keywords starting with * are only recognized by IE7, and keyword values ending with \9 (go figure!) are only recognized by IE8. Lastly, the MS filters only work on positioned elements; the zoom element satisfies this requirement.