How to Use the CSS Opacity Property

See CSS: Tips and Tricks for similar articles.

CSS3's opacity property makes it easy to change the opacity of images, text, <div>s, and other elements. Where before we might have resorted to images with a semitransparent alpha setting, we can now change the opacity via CSS. Even better, we can change opacity more easily with :hover to create rollover effects. Let's look at an example:

  1. Start with the following HTML page:
  2. 
    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="utf-8">
    	<title>CSS3 Opacity</title>
    	<style type="text/css">
    		#caption {
    			background: #fff;
    			width:300px;
    			position:relative;
    			top:-100px;
    			opacity: .5;
    		}
    		#caption:hover {
    		}
    	</style>
    </head>
    <body>
    <div id="main">
    	<h1>CSS3 Opacity</h1>
    	<img src="Images/chicago.jpg" alt="Chicago skyline" id="img1">
    	<div id="caption">The Willis Tower (formerly known as the Sears Tower) is 1450 feet tall.</div>
    </div>
    </body>
    </html>
    	
    If you open this page in a browser, it looks like this: web page before applying opacity
  3. The opacity property modifies the percent opacity of the element it's applied to. A setting of 0 means that the element should be invisible, and a setting of 1 means that it should be 100% opaque. To make the caption on the picture in our page semi-transparent, change its opacity to .5.
    
    #caption {
    	background: #fff;
    	width:300px;
    	position:relative;
    	top:-100px;
    	opacity: .5
    }
    The result will look like this: image with transparent caption
  4. To make the caption opaque (and easier to read) when the mouse hovers over it, you can use the :hover pseudo-class to change opacity to 1 on hover.
    
    #caption:hover {
    	opacity: 1;
    }
    
  5. Open the HTML page in a browser and hover your mouse over the caption to see it change.