In this tutorial we will be explaining the best way to add a gradient to the background of any webpage element using a method that improves page loading times over other method you may currently use simply by using CSS3 (with fall backs of course)
As designers we all use gradients in backgrounds all the time. To add texture to our designs or make our menu button look fancy for example.
Up until recently this has always been done with images and the most effect method involved just a small slice of a gradient image repeated up or across the image we are adding the background too. However this method involves loading the image (bandwidth) as well the server having to handle the request to get the image (HTTP requests). If we can remove these request particularly for popular website with large amounts of web traffic we should really be trying to do so.
Firstly we still need to make up the background image as we did in the past. This will only be used for browsers that are non-compliant. And we still embed it in the CSS stylesheet same as before.
body{
/* fallback/image non-cover color */
background-color: #1a82f7;
/* fallback image */
background-image: url(images/fallback-gradient.png);
}
This helps us to degrade gracefully in the event we hit a browser we hadn’t planned for. Rather than rendering the gradient it will using the image instead.
Then all we have to do is add the gradient rendering CSS code:
body {
/* fallback/image non-cover color */
background-color: #1a82f7; /* fallback image */
background-image: url(images/fallback-gradient.png);
/* Firefox 3.6+ */
background-image: -moz-linear-gradient(#2F2727, #1a82f7);
/* Safari 4+, Chrome 1+ */
background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#1a82f7), to(#2F2727));
/* Safari 5.1+, Chrome 10+ */
background-image: -webkit-linear-gradient(#2F2727, #1a82f7);
/* Opera 11.10+ */
background-image: -o-linear-gradient(#2F2727, #1a82f7);
}
Now when a browser loads the page it will look at the CSS it has and see the gradients and loads them instead of the images we used to use but if it can’t understand the gradient codes it will then render the image. Failing that it loads the background color.
Note: As the image is removed if you change the size of the element the gradient will change to match the size of whatever it is applied too.