Stretchy background gradient with CSS

In some cases, a design calls for a column with a background color blending into a gradient (or blending into gradient fading into white for a little "fade out" effect). That’s not terribly difficult to do when you’ve got a column with a fixed height: just cut a one-pixel-wide background image and use background-repeat:repeat-x in your CSS. That will create the effect you’re looking for: a full column width and column height gradient. But, what if you’re trying a background gradient in a column with a liquid height?

Here’s an example of what we’re trying to do, with CSS and HTML created by yours truly at the day job. Check out the left column. Essentially, we’re using the two-column layout described here and we’d like one of our liquid height columns to have a background gradient (or, in TheLadders example, a solid background color moving into background gradient fading out to solid white). It’s easy to do in four lines of CSS. This is the basic premise:

  1. The Setup: From your design, slice your gradient at the point where the solid background color ends and the gradient shift begins. Leave a pixel or two for a buffer. This will allow us to use CSS to specify the background color, and our gradient image to live as our gradient.
  2. The CSS: The CSS isn’t very complicated at all. You’ll just be letting background-repeat do its thing, and prevent your background gradient image from tiling. In our case, we’ll need to specifiy background-color, background-image, background-position, and finally background-repeat for the effect. By using these properties, we’ll ensure that we have a solid color and a non-tiled background sitting right at the bottom of our column, no matter how tall it gets.

What does all that code look like? Something like this:

div#leftColumn{
    background-color:#333;
    background-image:url(images/gradient.gif);
    background-position:bottom;
    background-repeat:no-repeat;
}

Pretty simple, eh? background-position ensures our gradient sits at the bottom of our column no matter how tall it is, while background-repeat ensures we only see it once. You’d like a top-down gradient? Use background-position top. As the example shows, we get a pretty little visual from some pretty short code.

One Response to “Stretchy background gradient with CSS”
  1. A Modern Fable (AJM) » Blog Archive » Equal-height, 100% height columns with CSS and JavaScript Says:

    [...] But what about that gradient? If you’ve been looking at the gradient here, you’re probably wondering how that shows up. Well, that’s a topic for another article coming soon. (It’s right here now.) [...]

I'm Reading…
Search This Site

AddThis Feed Button

Need great hosting?

Categories