JavaScript Tutorial JavaScript Examples CSS Tutorial HTML Tutorial About Us

Lesson 11: Opacity


We have learned how to add colors to a webpage using RGB codes, HEX codes and color names. However, using the aforementioned color systems only create solid colors for an element, in other words, they have 100% percent opacity. In this lesson, we shall learn how to control the opacity of a color so that the color displayed by an element can have a certain degree of transparency. There are two ways we can specify the opacity of an element, first is by using opacity property and the other one is by using the RGBA codes

11.1 The Opacity Property

In CSS, opacity is expressed in terms of decimal values ranging from 0 to 1, where 0 is 100% transparent, 0.5 is 50% opaque( or 50% transparent) and 1 is 100% opaque( or zero transparency).

The syntax of opacity is opacity:n; where the values of n range from 0 to 1. For example, the following CSS creates a box with red background of 50% opacity.

<div style="background-color: red; opacity: 0.5;position: static; width: 50px; height:50px;left:400px;top:1150px;"></div>

The following CSS creates a box with red background of 70% opacity.

<div style="background-color: red; opacity: 0.7; position: static; width: 50px; height: 50px; left: 400px; top: 1300px;"></div>
 

The following example shows two sets of overlapping boxes, the cyan box at the top has 100% opacity while the blue box has 0.3 opacity. Boxes at the bottom both have solid colors.

 

11.2 The RGBA Codes

The RGBA codes use a value to specify the opacity of a color. The syntax is rgba(r,g,b, a), where a indicates degree of opacity with values ranging from 0 to 1. For example, the following CSS creates a box with red background of 50% opacity.

<div style="background-color: rgba(255,0,0,0.5);position: static; width: 50px; height:50px;left:400px;top:2000px;"></div>

The following CSS creates a box with red background of 70% opacity.

<div style="background-color: rgba(255,0,0,0.7);position: absolute; width: 50px; height:50px;left:400px;top:2100px;"></div>


❮ Previous Lesson Next Lesson ❯


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy