In earlier lessons, we read about the
background property, along with
background-color properties. Instead of setting an image for a background, you can use a gradient too. Not using an actual image file but a gradient background, results in far better performance of the webpage and better control over the design.
So what is a Gradient? A gradient is one color fading into another. In CSS you can control the colors and the changing pattern of gradients to modify them the way you want.
Remember that we used
background-color to set the color of the background earlier. However for gradients we use
background-image: linear-gradient(red, orange);
This is the most common and useful gradient type. The gradients
axis can go from left-to-right, top-to-bottom, or at any angle you chose. If you do not declare an angle, the axis is assumed to be top-to-bottom. You can use hexa code or named colors or RGB values, to specify the colors.
background-image: linear-gradient(to right, red, #f06d06 );
To make it left-to-right, we pass an additional parameter at the beginning of the
linear-gradient() function arguments, by using the word to, indicating the direction, for example, "to right". This syntax works for corners as well.
For instance if you wanted the axis of the gradient to start at the bottom left corner and go to the top right corner, you could say "to top right".
You can use as many colors as you want to make a gradient.
background-image:linear-gradient(to right, red, #3366ff, rgb(255, 255, 0), green);
Live Example →
Radial gradient differs from linear in the way that it starts from a single point and spread outwards. Gradients are often used to simulate a lighting effect, so they can be useful to make a gradient seem even more natural.
The default setting is that the first color starts in the (center) of the element and fades to the end color towards the edge of the element. The fading happens at an equal rate no matter which direction. The default style of fading is an ellipse, but can be forced to a circle style too.
/* default ellipse */
background-image:radial-gradient(yellow, #3366ff );
/* changing the fading to circle form */
background-image:radial-gradient(circle, yellow, #3366ff );
Live Example →
The following browsers support both linear and radial gradients:
- Chrome 26+
- Firefox 16+
- IE 10+
- Opera 15+
- Safari 6.1+
There is also a third kind of gradient, that is,
repeating gradient. However not many browsers support this type as of now.
You can have a lot of fun with gradients. They are better options in terms of performance as compared to a
background-image and they look more natural.