CSS Gradient
Two types of gradients:
- Linear Gradients (goes down/up/left/right/diagonally)
- Radial Gradients (defined by their center)
CSS Linear Gradients:
To create a linear gradient you must provide at least two (or more) color stops.
Syntax:
background-image: linear-gradient(direction, color-stop1, color-stop2, ...);
Top to Bottom:
<!DOCTYPE html> <html> <head> <style> #grad1 { height: 200px; background-color: red; /* For browsers that do not support gradients */ background-image: linear-gradient(red, yellow); } </style> </head> <body> <h1>Linear Gradient - Top to Bottom</h1> <div id="grad1"></div> </body> </html>
OUTPUT:
Left to Right:
<!DOCTYPE html> <html> <head> <style> #grad1 { height: 200px; background-color: red; /* For browsers that do not support gradients */ background-image: linear-gradient(to right, red , yellow); } </style> </head> <body> <h1>Linear Gradient - Left to Right</h1> <div id="grad1"></div> </body> </html>
OUTPUT:
Using Angles:
Create an angle, instead of the predefined directions (to bottom, to top, to right, to left, to bottom right, etc.).
Syntax:
background-image: linear-gradient(angle, color-stop1, color-stop2);
Example:
<!DOCTYPE html> <html> <head> <style> #grad2 { height: 100px; background-color: red; /* For browsers that do not support gradients */ background-image: linear-gradient(90deg, red, yellow); } #grad3 { height: 100px; background-color: red; /* For browsers that do not support gradients */ background-image: linear-gradient(180deg, red, yellow); } #grad4 { height: 100px; background-color: red; /* For browsers that do not support gradients */ background-image: linear-gradient(-90deg, red, yellow); } </style> </head> <body> <h1>Linear Gradients - Using Different Angles</h1> <div id="grad2" style="text-align:center;">90deg</div><br> <div id="grad3" style="text-align:center;">180deg</div><br> <div id="grad4" style="text-align:center;">-90deg</div> </body> </html>
OUTPUT:
Using Multiple Color Stops:
<!DOCTYPE html> <html> <head> <style> #grad2 { height: 200px; background-color: red; /* For browsers that do not support gradients */ background-image: linear-gradient(red, orange, yellow, green, blue, indigo, violet); } </style> </head> <body> <h1>Linear Gradients - Multiple Color Stops</h1> <h2>7 Color Stops (evenly spaced):</h2> <div id="grad2"></div> </body> </html>
OUTPUT:
Using Transparency:
Which can be used to create fading effects.
Example:
<!DOCTYPE html> <html> <head> <style> #grad1 { height: 200px; background-image: linear-gradient(to right, rgba(255,0,0,0), rgba(255,0,0,1)); } </style> </head> <body> <h1>Linear Gradient - Transparency</h1> <div id="grad1"></div> </body> </html>
OUTPUT: