PHP Scripts and Resources for Webmasters

CSS Gradient Tutorial

Gradual changes in color, or gradient effects, are a common visual design element of Web 2.0 websites. Used appropriately, they can add a feeling of depth to a website and give it a more polished look. The most common method of accomplishing gradient effects is by using a background gradient image. There is also a proprietary gradient filter property in Internet Explorer that can be used to create gradient effects via CSS without the use of images. In this tutorial we will look at both methods of creating gradient effects.

Gradient Effects Using Background Images

First we will look at the background image method. This method will work equally well in Internet Explorer, Firefox, and most other major browsers. For our example, we will create a table and use a gradient on the header cells. The first step is to create a small background image containing the gradient. For this you will need a graphics editor such as Paint Shop Pro. To start, perform the following steps with your graphics editor:

You should end up with something like this: ../../tutorials/css-gradient/gradient.png

Now it's time for the code that demonstrates how to put our gradient image in the background of the table header. Create a valid web page that uses the following XHTML and CSS code, and save it in the same folder as your gradient image.

XHTML Code

<table id="gradientDemo">
    <tr>
        <th>Header 1</th>
        <th>Header 2</th>
    <tr>
    <tr>
        <td>Row 1</td>
        <td>Row 1</td>
    <tr>
    <tr>
        <td>Row 2</td>
        <td>Row 2</td>
    <tr>
</table>

CSS Code

#gradientDemo {
    border-collapse: collapse;
}
#gradientDemo td, #gradientDemo th {
    border: 1px solid black;
}
#gradientDemo th {
    background-color: #00c000;
    background-image: url(../../tutorials/css-gradient/gradient.png);
    background-repeat: repeat-x;
    background-position: top left;
}

You should see the following result:

Header 1 Header 2
Row 1 Row 1
Row 2 Row 2

Because we also set the background-color property, any content that goes beyond the height of the image will simply use the background color instead.

Gradient Effects Using the IE Gradient Filter

If you your visitors are primarily using Internet Explorer, you may opt to use the gradient filter property. This doesn't work in Firefox (or any other browser that I know of), so you'll probably also want to set the background-color to something appropriate for users of those browsers.

To see the gradient filter in action, change the style for the "th" element to the following:

CSS Code

#gradientDemo th {
    background-color: #8f7eac;
    filter: progid:DXImageTransform.Microsoft.Gradient(
        gradientType=0,startColorStr=#d8cde9,
        endColorStr=#8f7eac);
}

And the result this time is:

Header 1 Header 2
Row 1 Row 1
Row 2 Row 2

Firefox users will simply see a solid color in the header of the table above.

Back to Tutorials