The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1

114 Chapter 10


between full transparency (0.0) and full opacity (1.0). If you want an ele-
ment to have a foreground color of black at 50 percent opacity, you use the
following code:

E { color: rgba(0,0,0,0.5); }

As mentioned, rgba() differs from the opacity property in two ways:
First, rgba() is a color value, so you couldn’t, for example, use it to change
the opacity of an image (or an element with a background image). Second,
although the value of the rgba() function can be inherited, child elements
can overrule with an rgba() value of their own.
To more precisely illustrate the difference between the two, I’ll create
two identical code blocks using the following markup:

<div class="box">
<div class="text">
<h1>...</h1>
</div>
</div>

I’ll apply the following CSS rules to this markup: both elements will
get the same rules except that I’ll set the opacity of one and give an rgba()
value to the background-color of another, both with the same decimal frac-
tion value of 0.5:

.box { background-image: url('monkey.svg'); }
.text { background-color: white; }
.opacity { opacity: 0.5; }
.rgba { background-color: rgba(255,255,255,0.5); }

The results are shown in Figure 10-2, and the difference is pretty
clear. Both boxes have the same level of transparency, but in the first, the
opacity value has been inherited by its child p element, also making the text
semitransparent. In the second box, the rgba() value is applied strictly to
the background-color of the .text element, so the p element retains its fully
opaque black color.

Figure 10 -2: Comparing opacity (left) and RGBA (right)
Free download pdf