Pages

Monday, January 31, 2011

Making transparent your html element's background

For making a html transparent we have two ways-
   1. using a transparent PNG image as background
   2. using CSS for making that element transparent.



The problem with using opacity in CSS, besides the annoying syntax to cater to all web browsers, is that not only the background of the element will have transparency, but all of its child elements as well. This means that any text within will have the same opacity.





.trans {
opacity: 0.8;background: #999;filter: Alpha(Opacity=80);
}



The problem with PNG images is, beside a superfluous HTTP request, that images are way, way more larger in file size than one or two lines of CSS code – especially considering that the image has to be a bit larger.


Therefore, I can happily offer an alternative for you: RGBa colors. The beauty in this is that you declare the normal RGB values + values for the level of transparency you want, resulting in a very easy way to declare transparency for a color. Making this happen with CSS, with a fallback for those web browsers that doesn’t support it, would look like this:





.trans {
/* Fallback for web browsers that doesn't support RGBa */
background: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background: rgba(0, 0, 0, 0.6);
}



Shockingly enough (erm), no version of Internet Explorer supports RGBa colors (i.e. not IE 6, IE 7 or IE 8 at the time of this writing). However, and lucky for us, in year 2000 Microsoft went crazy with implementing various filters in IE. One of them are the gradient filter, and what we can do is use that and just define the same start and end color. “Ok, but how do I get the transparency”, you might be thinking now. The answer to that is that you will declare that as part of the color hex value. A CSS gradient filter achieving the same effect as the CSS code above would look like this:



1..trans {
2.filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
3.}



With all techniques learned above, let’s put it together in a working CSS rule:



01..trans {
02./* Fallback for web browsers that doesn't support RGBa */
03.background: rgb(0, 0, 0);
04./* RGBa with 0.6 opacity */
05.background: rgba(0, 0, 0, 0.6);
06./* For IE 5.5 - 7*/
07.filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
08./* For IE 8*/
09.-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
10.}