Not As Clear As It Seems: CSS3 Opacity and RGBA
One of the many things CSS lets us control is the opacity of elements, starting in CSS3. The opacity property is in fact one of the earliest and most widely implemented CSS3 properties. It has its problems though, but CSS3 also defines a more powerful way to control an element’s transparency: RGBA values.
The Opacity Property
To change the opacity of an element using the opacity property, you simply give it a value between 0 and 1 to determine the elements’ opacity. For example, if I want a div to be 50% transparent, I would give it the following style:
`
div {
opacity: .5;
color: #fff;
background-color: #000;
}
This works fine in Safari, Opera, and Firefox. Internet Explorer, however, doesn't yet support the opacity property. Instead, we have to use their proprietary property Alpha Filter. It's really not any more difficult than the opacity selector. One key thing to note hear though is that the Alpha Filter requires you specify the opacity on a scale of 0 to 100. There's even a catch to that though...the element is that you are applying the opacity filter to has to have a
hasLayoutvalue of true. While there are many ways of making an element have layout, some of the most common are to set a width, or give the element a zoom value of 1. So now our declaration is as follows:
`
`
div{
background: #000;
opacity: .5;
filter: alpha(opacity=‘50’);
zoom: 1;
}
` Simple enough…but with one catch that may or may not present a problem, depending on your situation. When you use the opacity property, the opacity is set for that element, and any children of that element. This can cause problems in readability and general appearance. If you do have problems in this situation, you may not have to resort to a PNG just yet.
More Power
CSS3 also allows for an extended version of the RGB color model that includes a fourth value that is used to specify opacity. Again, like the opacity property, the alpha value in the RGBA model accepts a value between 0 and 1. We can use an RGBA value anywhere that colors values are accepted in CSS: borders, background, font colors, etc. This already offers a higher level of control than the opacity selector.
Even better yet, while the opacity property defines the opacity for an element and all of its children, using the RGBA value only applies that transparency to the given property of an element that we specify. For example:
`
div{
background-color: rgba(0,0,0,.5);
color: #fff;
}
Some white text.