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

(C. Jardin) #1

112 Chapter 10


The opacity Property


Opacity is, strictly speaking, the measure of an object’s resistance to light—
the more opaque something is, the less light it lets through. An object with
no opacity is fully transparent.
In CSS, opacity is measured using the opacity property. In essence, with
opacity, you are setting how much of the background can be seen through
the specified element. The opacity property has the following syntax:

E { opacity: number; }

The number value is a decimal fraction—that is, a number between 0.0
and 1.0—where 0.0 is fully transparent, 1.0 is fully opaque, and any value
between those two is a blend of opacity and transparency. For example,
to set an element to be 50 percent opaque (or 50 percent transparent,
depending on whether your glass is half empty or half full), you use the
following rule:

E { opacity: 0.5; }

To further demonstrate, I’ll show a set of elements—a parent div, with a
child div, which in turn has a child p—repeated three times:

<div class="parent">
<div class="child">
<p>...</p>
</div>
</div>

I’ll apply the same rules to each set of elements, except for a change to
the opacity value. Here are the relevant rules for this example:

.parent { background-color: black; }
.child { background-color: white; }
.child.semi-opaque-1 { opacity: 0.66; }
.child.semi-opaque-2 { opacity: 0.33; }

You can see the output in Figure 10-1. The .child element in the first
(left) example has no explicitly set value for opacity, so it defaults to 1.0,
or fully opaque—its background is white. The next (middle) .child has a
value of 0.66, so its opacity is reduced by a third, causing the white back-
ground to appear as a light gray (a blend of the black background color
of the parent and the white background color of the element itself, which
shows through). Finally, the last (right) .child has an opacity value of 0.33,
so it can be considered two-thirds transparent, making the box a darker
gray color.
Free download pdf