My first Xaml/Silverlight post was on gradients, it seems only right that my first ASP.NET post should cover the same topic.
When .NET came out, I jumped over to ASP.NET, enjoying its power but struggling with its quirks.
I then got busy with WinForms and Silverlight development and ignored much of ASP.NET for the past few years. I just got back to it this week and was excited to see what has changed. Amazingly, not that much. I am surprised how many quirky things are still there.
Which brings us back to the topic at hand. 10+ years ago we achieved gradient backgrounds on our Web pages using a pencil thin gradient graphic repeated across the screen. Today, we achieve gradient backgrounds on our Web pages using a pencil thin gradient graphic repeated across the screen.
Funny, many of the forum posts on this topic these days say "use Silverlight instead", like that is something we can just decide to do. Well, maybe you can, but as a consultant I certainly can’t. And if you work in a corporate environment, I bet you can’t either.
So, here is the tried and true way to get a gradient background for your pages.
1) Create/buy/borrow an image file (such as a .jpg file) that contains a very thin sliver of the desired gradient.
My image file looks like this:
Yes, that is a little hard to see. But it is basically a very thin gradient line going from Red to White.
I found an online tool to help create this image file: SecretGeek’s Gradien-Maker. It looks a little loud when you first access the page, but it allows you to easily create a gradient. You can get the gradient just like you want it, then Save Background As to generate the image file with a pencil thin piece of the gradient. It worked great.
NOTE: This does not allow for setting specific gradient stops or for anything but a linear gradient, but it works for simple vertical or horizontal gradients.
2) Define the style
Define the style in a cascading stylesheet (CSS) like this:
[If you are not familiar with HTML or CSS, see the above referenced book.]
This sets the URL of the background image to my gradient image file. It then sets it to repeat across the x-axis. This causes the sliver to be repeating horizontally across the page.
3) Set the new style on the desired HTML element in the ASP.NET page.
I added it to the Body element as follows:
You can forget about step #2 and put the style directly in the ASP.NET page:
<body style="background-image: url(Images/Gradient2.jpg);background-repeat: repeat-x;">
In either case, the result is something like this:
You can make the gradient longer or shorter by creating a new gradient image file with a different size. Or you can use a similar technique to create a horizontal gradient repeated vertically across the page.
Until we are all doing Silverlight or ASP.NET comes out with gradient features on its controls, this is the best technique I’ve found to put gradients on Web pages.