How to work with gradients in CSS3

How to work with gradients in CSS3

CSS3 gradients are used to display smooth transitions between two or more colors. Images were used earlier to display effects, but now in CSS3 we can use gradients. Gradients save bandwidth and load time. In a previous tutorial you learned about CSS3 Pseudo classes. In this tutorial we are going to learn how to work with gradients in CSS3. Gradients can be used with background property. All modern browsers support gradients.

CSS3 provide two types of gradients.

Linear Gradient

Radial Gradient

Linear Gradients in CSS3

To create a linear gradient, you have to define at least two color stops. Color stops are the colors that we want to transition.

Syntax of Linear Gradient

1

background:linear-gradient(direction,color-stop1,color-stop2,...);

We define a direction and color stops with comma separated values.

Linear Gradient – Top to bottom

Consider the HTML page below.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport"content="width=device-width">

<title>JSBin</title>

<style>

div{

height:200px;

width:200px;

}

.gradient {

background:linear-gradient(red,yellow);/* Standard syntax */

}

</style>

</head>

<body>

<div class="gradient"></div>

</body>

</html>

You can also provide direction of gradient, by default it is top to bottom.

1

2

3

.gradient{

background:linear-gradient(red,yellow);/* Standard syntax */

}

Linear Gradient – Left to Right

Gradients can be from left to right, so we use to right.

1

background:linear-gradient(toright,red,yellow);/* Standard syntax */

Using Angles in linear gradients in CSS3

Angles can also be used in a linear gradient. Instead of using directions like to bottom, to top, to right, to left, to bottom right. Consider the code below.

1

background:linear-gradient(angle,color-stop1,color-stop2);

1

background:linear-gradient(-90deg,red,yellow);/* Standard syntax */

This code generates a linear gradient in -90 degree angle.

Linear Gradient with multiple color stops

Multiple colors can be added as color stops in a linear-gradient. Below is a linear gradient from left to right with multiple color specified.