Kimler Sidebar Menu

Kimler Adventure Pages: Journal Entries

search cloudRandom Searches
random top 40

Playing with Opacity

Filed in:CSS
Web Dev·The Web

Playing with Opacity

May 29th, 2008  · stk

Opacity is a CSS3 directive, but there's no reason not to start using it today. Apply it against the major browsers, validate it against the W3C CSS validator and I'll even show you a great "Before & After CSS Opacity Technique" for displaying your before-after photos

opacity overlay

hover to read

Using the CSS3 "Opacity" Directive: Future-Proof, Valid CSS and No CSS Hacks

opacity sidebar

The "Opacity" CSS directive is part of the CSS "level 3" Color Module, which is a "Candidate Recommendation". In a nutshell, this means that opacity isn't "ready for prime time".

Darn and phooey! You like opacity. And why not? It's fun to play with and you can achieve some nifty web effects using opacity. (I'll demonstrate an opacity technique that provides a great CSS-only way of showing "before" and "after" photos!)

Enjoy the MAGIC of Valid CSS3 Today!

What is opacity? Well, it's the opposite of transparency. Something that has 100% opacity is 0% transparent. Likewise, something with 0% opacity is 100% transparent.

The W3C (World Wide Web Consortium) recommends thinking of opacity as a post-processing operation. After an element (including it's children) is rendered into an image for the computer monitor, the opacity setting specifies how to blend the element into the final display.

Applying opacity to an element is easy. Simply specify the "opacity" directive to a selector and provide a value from zero to 1.0, where zero is completely transparent and 1.0 is completely opaque.

Of course, the difficulty is that the level 3 CSS candidate recommendations are only honored by a select number of web browsers, notably current versions of FireFox, Opera, Safari & Netscape. As usual, the Grand Pubah of browsers (Microsoft's Internet Explorer), doesn't adhere to this as-yet approved CSS directive.

That's the bad news.

The good news is that I'm here to tell you that if you want to use opacity for your web pages - you can! We have been for some time!

There's a way to use opacity for FireFox, Opera, Safari, as well as Internet Explorer 6 and Internet Explorer 7. (According to AWSTATS, a web server statistics program, 97% of our 113,728 April visitors used one of these browsers ... heck, that's about as close to "everyone" as you're going to get in this cross-browser world of ours!).

There's even a way to use opacity so that the CSS validates (to verify this, just click on the "CSS" validation button in the footer below)!

Best yet, it's completely future-proof and requires no CSS hacks.

OKAY ... you're primed and ready. You want to start using opacity.

All you have to do is read on, Cascading Style Sheet lovers ... read on ...

Opacity for the Major Browsers

clearing before clearing after

12-year-old Afghan refugee, shot by National Geographic photographer Steve McCurry. Hover to see her at 30 years of age. (Demo of "Before-After Opacity CSS")

Using the CSS3 opacity directive is easy and it's completely future-proof, assuming that it's accepted without changes, which is probably a safe bet. Unfortunately, this only targets modern browsers, such as current versions of FireFox, Opera, Safari & Netscape (which accounts for roughly 30% of our current traffic).

Unfortunately, if a browser doesn't render opacity properly, the results are awful. Visitors might not be able to SEE the content you have, under a nearly transparent element, if their browsers don't understand the directive! Not very accessible at all.

When you use opacity, it's important to insure that the majority of visitors browsers will render it properly. The first step, is getting Internet Explorer to play nice.

The good news is that Internet Explorer already has a proprietary CSS extension that duplicates the opacity directive. IE has a way of creating effects using visual filters and transitions. (You can demo all the variations of filters and transitions at this demo site).

I wouldn't normally recommend using these IE-only CSS extensions for your website, but there's one extension that will mimic the CSS3 opacity directive and it comes in handy here. It's called the "Alpha Filter" and it can be easily applied in CSS file.

Code:

#selector {  
  opacity:0.7;                    /* Modern Browsers */  
  filter:alpha(opacity=70);       /* IE 5.5, IE6 & IE7 */  

 

With these two CSS directives, you're hitting IE5.5, IE6, IE7 and "modern browsers" (i.e., current versions of Safari, Opera, Firefox and Netscape). Together, these account for roughly 97% of our visitors. That's generally what we shoot for - the "majority". (The way I see it, you can kill yourself, trying to get the last 3% or so, or make get the big percentage without a lot of fuss.)

The reason I say this this is "future-proof" is that IE6 and IE7 will never understand the "opacity" rule and who knows about IE8? But it doesn't matter, IE8 will either continue to understand the filter directive or understand the "opacity" rule ... either way, you're covered.

If you really want to hit a few more browsers (and don't care about CSS validation), you can also add these additional directives:

Code:

#selector {  
  -moz-opacity:0.7;      /* older Mozilla browsers, older versions of Netscape */  
  -khtml-opacity:0.7;    /* old versions of Safari (1.x) */  
  

Validating the CSS Opacity Directives

clearing after clearing before

Hover over the photograph to see how much wood Scott could chuck, when he made like a woodchuck and chucked wood.

Sure, you could put all four directives listed above, into your CSS and the various browsers will "see what they understand" and your elements will have the opacity you specify and visitors won't know the difference. But if you try to validate your CSS at the W3C CSS Validator, they'll have errors.

Heck, even if you try to use the "pure" CSS3 directive "{ opacity:0.7; }", the page will likely have errors.

While validation isn't the end-all, be-all, I make an effort to write valid XHTML and CSS code and seeing a green "Congratulations" makes me happy.

If you wish to achieve CSS validation, then this section is for you, as there are a few easy steps required to obtain validation.

Don't Cater to Old Browsers

Personally, I don't like supporting way-old browsers. Maybe if people had to buy them, I would, but they're free, updates are available and I think visitors should be using the latest thing (listen up IE6 - and less - users ... I'm talking to you! ... If you're using IE6 (or *gasp* - a lower version), you should really upgrade to IE7 or buy a new computer).

Target Internet Explorer

One of the few GOOD things about Internet Explorer (and I wish that other browsers had this) is that there's a method of targeting IE only and even specific IE versions. The built-in method is called "IE conditional comments" and it's very useful.

These comments can be added anywhere in the document (i.e., either to the <head> or <body>). The bonus with IE conditional comments, besides their specific targeting, is that any CSS they contain, isn't "seen" by the W3C CSS validator.

Because the IE-only filter CSS extensions are understood by IE5.5 through IE7 versions, it's easy to simply apply it to every version of IE, using the following code:

Code:

<!--[if IE]>  
  <style type="text/css" media="screen, projection">  
    #selector {  
      filter:alpha(opacity=70);  
    }  
  </style>  
<![endif]--> 

 

Validate Against CSS3, not CSS2

While the above bits hide the IE-only CSS extensions from the W3C CSS Validator, one still gets errors using the CSS3 opacity directive. "Sorry! We found the following errors (#)"

The reason for this is that the W3C CSS Validator, by default, checks for errors using the CSS2 recommendation, not the CSS3 candidate recommendation. It is, however, possible to switch this, by using a special URL parameter called "profile".

There's two ways to invoke this:

At the W3C Validator Site: Select "More Options" at the front page of the W3C CSS Validation page. When you do, you see that "CSS level 2.1" is selected as the default profile. Change this to "CSS level 3", plug in the page that uses an opacity directive and blammo, you pass!

As a link: If you want to link a page (or template) to the W3C Validator (like the way we do in our footer), just use a special URL parameter in the link:

Code:

<a href="http://jigsaw.w3.org/css-validator/check/referer?profile=css3" title=" validate this page ">valid CSS</a> 

 

Just drop the code above into your XHTML page or template and the W3C CSS Validation service will check the referring URL (the page) and apply the "CSS level 3" profile.

 

Time to Play with Opacity

Now that 97% (or thereabouts) of visitors can see it and you've got a way use opacity without breaking CSS validation, it's now time to play!

The "Before & After Opacity Technique" XHTML:

You've seen the two demonstrations above: the haunting eyes of the 12-year-old Afghan girl; and a pile of wood I've cut and cleared from our 5-acre property.

The number of uses for this "Before-After Opacity CSS" are limited only by your imagination and now that you've got opacity up and running, there's no excuse not to use it!

The XHTML code is startling simple: Just two photos and a paragraph wrapped in a <div>:

Code:

<div class="afghan_girl bef-aft left">  
  <img class="after" src="after.jpg" alt="before" title="" />  
  <img class="before" src="before.jpg" alt="after" title="" />  
  <p class="caption">12-year-old Afghan refugee, shot by National Geographic photographer Steve McCurry.  Hover to see her at 30 years of age. (Demo of "Before-After Opacity CSS")</p>  
</div> 

 

There are three class names associated with the <div>:

  1. a unique class name (which specifies the image width and caption styling in the CSS);
  2. a generic "bef-aft" class name (which specifies repeated CSS directives, which is useful if you're putting more than one such image on a page) and
  3. a left|right choice class name, which allows you to float the image to the left side (or right side) of a page.

The "Before & After Opacity Technique" CSS:

The CSS is a tad more involved, but easily applied and changed for multiple images on a page:

Code:

/* Before & After Opacity Technique */  
/* © www.randsco.com */  
 
/* change these */  
.afghan_girl {  
  width:400px;  
}  
.afghan_girl .caption {  
  width:380px;  
  background:#333;  
  color:#ca5;  
}  
 
/* leave alone */  
.bef-aft {  
  position:relative;  
}  
.bef-aft.left {  
  float:left;  
  margin:0 10px 0 0;  
}  
.bef-aft.right {  
  float:right;  
  margin:0 0 0 10px;  
}  
.bef-aft img {  
  display:block;  
}  
.bef-aft .caption {  
  padding:5px 10px;  
}  
.bef-aft .before {  
  position:absolute;  
  top:0;  
  left:0;  
}  
.bef-aft .before:hover {  
  opacity:0;  

 

Basically, the way this works is that the "before" image is positioned on TOP of the "after" image. When a visitor hovers over the "before" image, its opacity is changed from the default (1.0) to being completely transparent (0). Simple eh?

If you're adding more than one "Before & After Opacity Technique" picture to a page, you'll just need to create a unique class name for each one, and change the bits in the two selectors at the top (picture-specific widths, plus any additional caption styling you want). That's it. (Note: if all your images are identical in size and you're happy having one caption style, you don't need a unique class names for each one. The above CSS will work for ALL the images. ;) )

Of course, the above "opacity" directive targets only the modern browsers that understand it. You'll need to include an IE conditional comment, so that Internet Explorer versions 5.5, 6 and 7 use their own proprietary "Alpha Filter" to achieve the same effect. In the CSS for this page, you'll find the following:

Code:

<!--[if IE]>  
  <style type="text/css" media="screen, projection">  
    .bef-aft .before:hover {  
      filter:alpha(opacity=0);  
    }  
  </style>  
<![endif]--> 

 

IE6 ... The Un-:hover-able Browser

Astute readers will have noted that the opacity is set to kick in when the <img> tag is hovered, which is something that IE6 will never do, because IE6 only provides the :hover pseudo-class for the anchor, or <a> tag.

Back in the day when IE6 was King, I'd have worked really hard to put all the above XHTML inside of an <a> tag, so that IE6 (and every other browser) would do the hover deed. My support for IE6 sorta stopped after IE7 came out. Now, I rely on an IE-only Dynamic HTML behavior file, which has an HTC file extension. It's inner workings are a bit of a mystery to me. All I know is that it provides IE6 the ability to apply :hover pseudo-classes to IE6 elements other than <a> tags - like its bigger brother - IE7.

I kick the IE6 behavior thing off with the following IE Conditional Comment (which loads by default) in the <HEAD> section of all of the Randsco.com pages. This IE Conditional Comment targets all versions of IE less than IE7:

Code:

<!--[if LT IE 7]>  
  <style type="text/css" media="screen, projection">  
    body { behavior:url("csshover.htc"); }  
  </style>  
<![endif]--> 

 

You may want to nab the csshover.htc file for your own use, no modifications are needed.

 

Conclusions

OKAY ... I've showed you a few fun demos, explained how to get opacity working for a majority of your website visitors, showed you how to get it to pass CSS validation and given you some fun XHTML / CSS code for the "Before & After Opacity Technique".

You're happy, right?

Before I wrap up, I should mention that this technique, like all randsco.com scripts and techniques, is free for your personal use. This isn't the case for commercial use, as we require a donation. ;) Check our our copyright page for more detail, or to donate to the cause.

As always, if you have any questions or need help deploying the technique, just contact Scott

I'll close and get this posted, and worry about the "Resources" section later.

 

Additional Reading / Opacity Resources

W3C CSS3 "Color Module"
(Permalink)
Views: 49726 views
9 Comments · GuestBook
default pin-it button
Updated: 30-May-2008
Web View Count: 49726 viewsLast Web Update: 30-May-2008

Your Two Sense:

XHTML tags allowed. URLs & such will be converted to links.


Subscribe to Comments

Auto convert line breaks to <br />

1.flag Gary Comment
05/30/08
Scott, you certainly know your stuff. It was very informative and a good read and I am looking forward in having a play with Opacity.

I made a website for someone a year ago or so and used opacity, just to find that it didn't work in IE as I hoped and the CSS didn't validate, so I can't wait to get stuck into it now.

Look out world, I am primed and ready to go :)

Hope you are not 'grafting' too hard today !

Gz



2.flag stk Comment
05/30/08
Hopefully, you'll have better luck using opacity now. ;)

LOL @ grafting. No, the hard work comes tomorrow, when I'm back on a chainsaw at the U-Cut place. :p
3.flag Gary Comment
05/30/08
Hope its a good day lumberjacking :)

Gz
4.flag Gary Comment
06/03/08
Hi Scott, How did the tree cutting go last Saturday, did you get a full van full again ? and did you remember your dinner !

Gz
5.flag stk Comment
06/03/08
LOL ... just posted. ;)
6.flag css-resources Comment
06/17/09
Great work, Scott! I sure hope you upudate this page now that IE8 is out, because they did exactly what everyone feared most with opacity: made the situation even WORSE!

How would you adjust your codes on this page for IE8--tell the browser to use IE7 emulation mode?
7.flag stk Comment
06/17/09
css-resources - Hmmm ... I have upgraded to IE8 and checked this page, at your urging, and it renders fine. I don't understand what you're on about, as opacity renders identical to IE7?!
8.flag Livy Comment
08/23/12
Alright I'm trying to make my navbar background color opaque and even if I just chuck in
opaque: 0.9; blah blah whatever else I have its not working!!
9.flag stk Comment
08/24/12
Livy - CSS (like most computer stuff) is very persnickety. Try "opacity" in place of "opaque".