Smart Gradients in CSS3

Hello everybody. I assume that most of you have used or experienced with gradients in CSS3.

I Want to show you small trick, how to make one gradient that is relevant for making multiple gradients, without the need to rewrite.

In one of my project, I realized that most of the gradient are almost the same. all of them where with one color that get darken or lighter color of themselves, and I thought it’s silly to make each color new gradient. Instead we can make one gradient that we will use for all “gradients”.

How it’s done, Lets begin!

I made common buttons in the HTML and gave them common class-name and specific class-name and some styles to decorate the button.

HTML

<a class="button button1">button 1</a>
<a class="button button2">button 2</a>
<a class="button button3">button 3</a>
<a class="button button4">button 4</a>
<a class="button button5">button 5</a>

CSS

.button{ 
float:left;
height:40px;
line-height:40px;
margin-right:20px;
padding:0 15px;
color:#fff;
font-weight:bold;
font-size:16px;
font-family:arial;
background-color:#555;
border-radius:5px;
border:solid 1px rgba(0,0,0,0.5);
}

I gave every button unique color(regular background-color).

CSS

.button1{ background-color:orange; }
.button2{ background-color:red; }
.button3{ background-color:green; }
.button4{ background-color:RoyalBlue; }
.button5{ background-color:OrangeRed; }

Now, to make all of them to gradients is very easy. Instead of using full colors for the gradient, like red and darken red, I used gradient with background-color of black with opacity of 0% till background-color black with opacity of 65%.

I added this gradient with transparency to the common button class.

CSS

.button{ 
background-image: linear-gradient(rgba(0,0,0,0) 0%,
rgba(0,0,0,0.65) 100%);
}

Yeay! we made multiple visual gradients with using only one gradient in the CSS!

Now if you wand to had hover styles, just put the gradients color reverse, like this:

CSS

.button:hover{ 
background-image: linear-gradient(rgba(0,0,0,0.65) 0%,
rgba(0,0,0,0) 100%); /* W3C */
}

LIVE EXAMPLE

That’s it, Enjoy!

Elad Shechter.

Originally published at coderwall.com by me, on Jun 2, 2013.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.