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 work­ing with gradi­ents, I often see the fol­low­ing:

.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 col­our of the ele­ment to red. That means chan­ging four val­ues, ugh.

Try using transparent gradients

Here is an easi­er 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 trans­par­ent gradi­ents halves the num­ber of val­ues that need updat­ing if the col­our changes!

For those of you that noticed the use of hsla(0,0%,100%,0) instead of transparent, have a read of this art­icle that explains the subtle dif­fer­ence.

Addendum

As Justin poin­ted out in his com­ment, we can take this even fur­ther: by hav­ing the gradi­ent over­lay become light­er on hov­er, we only need to declare a single back­ground col­our! 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 fur­ther. Rather than alter­ing the back­ground col­ors when the state of an ele­ment is changed, alter the gradi­ent itself. Now, you have only the root col­or to change. This works when the you’re not chan­ging the col­or, but chan­ging the bright­ness (up or down) of the col­or, which is almost always the case.

    Here’s an example:

    .foo {
    back­ground-col­or: blue
    back­ground-image: linear-gradient(hsla(0,0%, 100%, 0.1), hsla(0,0%, 100%, 0));
    }

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

    This meth­od has saved me many times dur­ing small redesigns to com­plex UI’s. Hope it helps!

  2. Joshua Hibbert

    Great advice Justin. Simplifying even fur­ther; it seems so obvi­ous now that you have men­tioned it to me!

  3. BigBossSNK

    back­ground-col­or change on hov­er is
    syn­tactic­ally clear­er AND
    allows a trans­ition to occur.

    I don’t see a bene­fit to switch­ing lin­ear-gradi­ent on hov­er