Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

172 CHAPTER 4 Getting started with CSS3


Using transparency
You can set the CSS opacity property to control the amount of transparency an element has.
This is especially useful when content is placed over an image and you still want to see the
image. The opacity must be a value between 0.0 and 1.0, where 0.0 is invisible and 1.0 is
opaque. In the following example, the opacity of an element whose id is mainContent is set so
the element is 50 percent see-through and anything under that element is still visible.
#mainContent {
opacity: .5;
}

Using the rgba function
The rgba function is similar to the rgb function except it has an alpha parameter, which rep-
resents the amount of transparency to use. The alpha parameter value must be between 0.0
and 1.0, where 0.0 is invisible and 1.0 is fully opaque. The following are examples of using the
rgba function.
h1 { background-color: rgba(255,0,0,0.5); }
h1 { background-color: rgba(0,255,0,1); }
h1 { background-color: rgba(20%,50%,0%, 0.2); }

Using the hsl function
Another way to represent a color in CSS3 is to use hue-saturation-lightness (HSL) colors. Like
RGB colors, HSL colors use three numbers, but the numbers are for hue, saturation, and light-
ness. The hue is calculated as an angle of the color circle where red is 0 or 360 (degrees), and
other colors are spread around the circle, as shown in Figure 4-8. As you look at the degrees
in the circle, yellow can be represented as 60, as –240, or even as 420. You can normalize the
value by using the (((x mod 360) + 360) mod 360) formula. The reason for adding 360 and
performing a second modulus is to handle negative values.
The saturation and lightness values are represented in percentages. Saturation is the
amount of color to provide, and lightness is the amount of lightening to provide. It’s easy to
produce matching colors by keeping the hue value the same and adjusting the saturation
and lightness to get the desired colors. Primary colors typically have a saturation value of 100
percent and a lightness value of 50 percent. Some examples of HSL are as follows.
h2 { color: hsl(60, 100%, 50%); } /* yellow */
h2 { color: hsl(120, 100%, 25%); } /* dark green */
h2 { color: hsl(0, 100%, 50%); } /* red */
Free download pdf