A Quick Tip when Working with Colour Gradients in CSS

A Quick Tip when Working with Colour Gradients in CSS

This post will take less than a minute to read.

Creating gradients in CSS

When working with gradients, I often see the following:

.foo {
    background-image: linear-gradient(lightBlue,
                                      blue);
}
.foo:hover {
    background-image: linear-gradient(lighterBlue,
                                      lightBlue);
}

That doesn’t look that bad does it? Imagine that you have to change the colour of the element to red. That means changing four values, ugh.

Try using transparent gradients

Here is an easier way to handle the above:

.foo {
    background-color: blue;
    background-image: linear-gradient(hsla(0,0%,100%,.1),
                                      hsla(0,0%,100%,0));
}
.foo:hover {
    background-color: lightBlue;
}

Using transparent gradients halves the number of values that need updating if the colour changes!

For those of you that noticed the use of hsla(0,0%,100%,0) instead of transparent, have a read of this article that explains the subtle difference.

Addendum

As Justin pointed out in his comment, we can take this even further: by having the gradient overlay become lighter on hover, we only need to declare a single background colour! Here is an example:

.foo {
    background-color: blue;
    background-image: linear-gradient(hsla(0,0%,100%,.1),
                                      hsla(0,0%,100%,0));
}
.foo:hover {
    background-image: linear-gradient(hsla(0,0%,100%,.2),
                                      hsla(0,0%,100%,.1));
}

Tweet this

5 Comments

  1. Cerebrl

    This is really great advice, although I’d go one step further. Rather than altering the background colors when the state of an element is changed, alter the gradient itself. Now, you have only the root color to change. This works when the you’re not changing the color, but changing the brightness (up or down) of the color, which is almost always the case.

    Here’s an example:

    .foo {
    background-color: blue
    background-image: linear-gradient(hsla(0,0%, 100%, 0.1), hsla(0,0%, 100%, 0));
    }

    .foo:hover {
    background-image: linear-gradient(hsla(0,0%, 100%, 0.2), hsla(0,0%, 100%, 0.1));
    }

    This method has saved me many times during small redesigns to complex UI’s. Hope it helps!

  2. Joshua Hibbert

    Great advice Justin. Simplifying even further; it seems so obvious now that you have mentioned it to me!

  3. BigBossSNK

    background-color change on hover is
    syntactically clearer AND
    allows a transition to occur.

    I don’t see a benefit to switching linear-gradient on hover