Click here to Skip to main content
15,867,453 members
Articles / Web Development

CSS3 for Beginners: Color and Opacity

Rate me:
Please Sign up or sign in to vote.
4.59/5 (18 votes)
27 Sep 2011CPOL5 min read 63.6K   34   8
The CSS3 Color Module is now a W3C Recommendation. Let's see what that means for your sites.

Introduction

Originally published as a W3C Recommendation in 1996, Cascading Style Sheets (CSS) have endured as the best way of defining the rendering of content separate from its markup. Nearly 15 years later, CSS level 3 (CSS3) is making new design features available to web developers. We’ll take a look at some of the most interesting and popular of those features.

If you’re not already familiar with CSS, a good place to start is the article CSS For Beginners by Nongjian Zhou. It provides a handy primer to CSS syntax, common selectors and techniques for adding CSS to your HTML files.

It’s important to note that CSS3 is still in Working Draft status and not yet a final – and stable – W3C Recommendation. One new aspect of CSS3 is that proposed new features have been broken out into more than 40 modules. Some modules are extremely experimental, while others have become pretty stable and are being implemented in new browser releases. The CSS3 Color Module has become an actual W3C Recommendation.

In an effort toward “standards compliance,” most current browsers now support many features described in the CSS3 Working Drafts, but you’ll be wise to keep in mind that these features and their implementations can change. Test, test and test again before using these features in your production code.

In this article, we’ll take a look at the CSS3 Color Module as it’s much more solid than the other proposals and experimental features. In fact, as of June 2011, it’s an official W3C Recommendation. The new CSS3 Color features include HSL color specifications in addition to traditional hex and RGB values, as well as the ability to directly specify opacity and alpha channels

HSL Colors

There are traditionally been a number of ways to specify colors in both HTML markup and CSS. These include:

  • Color keywords (aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow)
  • Hexadecimal values
  • RGB values

Here are some quick examples:

CSS
.keyword { color: white; }
.shorthex { color: #FFF; }
.longhex { color: #FFFFFF; }
.rgb1 { color: rgb(255, 255, 255); }
.rgb2 { color: rgb(100%, 100%, 100%); }

CSS3 adds the ability to specify colors via hue, saturation, and light (HSL) values in the format.

CSS
.example { color: hsl([hue], [saturation], [light]); }
.implemented { color: hsl(240, 50%, 80%); }

Hue represents the color expressed in degrees around the color wheel. The W3C documentation provides some helpful tables of hue and saturation values that you can use for reference, and there are numerous online tools for generating hue values as well.

Saturation represents the amount of color in percent, where 0% is completely desaturated (grayscale) and 100% is fully saturated (the chosen color in all its vibrant glory).

Light represents the brightness of the color in percent, where 0% is no brightness (black) and 100% is all brightness (white).

A great tool for experimenting with HSL colors is the HSL Color Picker, which lets you choose a color and then copy-and-paste the hex, HSL/HSLa or RGB/RGBa representation. (Hat tip to member HasmoreJohn for the suggestion and link.)

Here we have a few examples showing blue (hue = 240) text with varying levels of saturation.

CSS
#left { color: hsl(240, 0%, 50%); }
#center { color: hsl(240, 50%, 50%); }
#right { color: hsl(240, 100%, 50%); }

Which equates to the following color rendering for the text:

Saturation.png

Likewise, we can adjust the lightness values:

CSS
#left { color: hsl(240, 100%, 0%); }
#center { color: hsl(240, 100%, 50%); }
#right { color: hsl(240, 100%, 100%); }

The results look like this:

Lightness.png

So that gives you five different ways to specify element color in CSS. I’ve just demonstrated text coloration here, but of course the same applies to any other element that can take color styling such as backgrounds and borders.

As for color palette selection and taste… I leave that as an exercise for the reader.

Opacity and Gradients

Another color-related feature of CSS3 is support for alpha channels and opacity. Basically, this gives you the ability to control the transparency of any element – from text to backgrounds to entire divs – from completely opaque to completely transparent, and any state in between.

To demonstrate, let’s begin with a simple div containing some text.

HTML
<div id="container1">
    <span id="left">I</span>
    <span id="center">&hearts;</span>
    <span id="right">Opacity</span>
</div>

We’ll start with an example that has no opacity setting, then we’ll add a variation that uses sets opacity for the entire div. (Note that I’m leaving some styling out for clarity, such as width, alignment and so on.)

CSS
#noopacity { background: silver; }
#basicopacity { background: silver; 
                opacity: 0.7;
                -moz-opacity: 0.7;
                -webkit-opacity: 0.7;
                -khtml-opacity: 0.7; }

As you can see here, we use an opacity setting. Opacity values range from 0.0 (completely transparent) to 1.0 (completely opaque). In this case, we’ve applied the opacity to the entire div, text and all. We also included -moz, -webkit and -khtml prefixed settings for compatibility with FireFox, Safari/Chrome and legacy Safari browser implementations. The results look like this:

basicopacity.png

That’s not really a CSS3 thing. However, CSS3 does enable specifying the opacity as an alpha channel in RGBa or HSLa color settings. In this case, you use either rgba instead of rgb or hsla instead of hsl for the setting and add a fourth parameter for the alpha channel (opacity) value. For example, let’s apply opacity just to the background of the div:

CSS
#rgbaopacity { background:rgba(192, 192, 192, 0.7); }

The result is straightforward. Note that the text in this case retains full opacity, while the background has become somewhat transparent.

rgbaopacity.png

Gradients are another CSS3 feature you can start using, though implementation is different across browsers and you need to apply brower-specific prefixes. However, the various gradient implementations do accept color specifications using all the CSS3 techniques from reserved color keywords to RGBa and HSLa.

CSS
#lineargradient {
    background: -moz-linear-gradient(top, silver 0%, white 100%);
    background: -webkit-gradient(
        linear, left top, left bottom, from(silver), to(white));}

In this case, we just transition from silver to white. However, it’s completely possible to employ alpha channels to employ transparency in the gradient.

CSS
#container5 {
    background: -moz-linear-gradient(
        top, rgba(192, 192, 192, 0.8), rgba(255, 255, 255, 0.0));
    background: -webkit-gradient(linear, left top, left bottom, from(
        rgba(192, 192, 192, 0.8)), to(rgba(255, 255, 255, 0.0)));}

Here you can see both the standard linear gradient and a version transitioning from semi-opaque silver to completely transparent white.

gradients.png

The CSS code becomes rather more complicated, but there is also a great deal of flexibility in specifying vertical, horizontal and even radial gradients, using multiple colors and levels of transparency.

For more on the intricacies of gradient syntax and additional features you can employ, see the Mozilla developer documentation for Using gradients and the Webkit.org documentation on CSS3 Gradients.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Writer ContentLab
United States United States
Terrence Dorsey is a technical writer, editor and content strategist specializing in technology and software development. He is currently Senior Technical Editor at ContentLab. He previously was Senior Technical Writer at ESPN, Director of Content Development at CodeProject and Senior Editor of MSDN Magazine and TechNet Magazine. His writing has appeared in Visual Studio Magazine, MSDN Magazine, Application Development Trends and Redmond Magazine.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Sunasara Imdadhusen29-Sep-11 2:24
professionalSunasara Imdadhusen29-Sep-11 2:24 
SuggestionHSL Color Picker Pin
HasmoreJohn27-Sep-11 9:39
HasmoreJohn27-Sep-11 9:39 
GeneralRe: HSL Color Picker Pin
Terrence Dorsey27-Sep-11 10:23
sitebuilderTerrence Dorsey27-Sep-11 10:23 
GeneralRe: HSL Color Picker Pin
HasmoreJohn27-Sep-11 18:16
HasmoreJohn27-Sep-11 18:16 
GeneralMy vote of 4 Pin
Fabio Franco22-Sep-11 9:52
professionalFabio Franco22-Sep-11 9:52 
GeneralRe: My vote of 4 Pin
Terrence Dorsey27-Sep-11 10:26
sitebuilderTerrence Dorsey27-Sep-11 10:26 
GeneralRe: My vote of 4 Pin
Fabio Franco27-Sep-11 10:45
professionalFabio Franco27-Sep-11 10:45 
GeneralMy vote of 5 Pin
SanjeevSingh15-Sep-11 2:24
SanjeevSingh15-Sep-11 2:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.