How to Use HSL Color in CSS: Simple Guide with Examples
Use the
hsl() function in CSS to define colors by hue, saturation, and lightness. The syntax is hsl(hue, saturation%, lightness%), where hue is an angle from 0 to 360 degrees, and saturation and lightness are percentages.Syntax
The hsl() function in CSS defines colors using three parts:
- Hue: a number from 0 to 360 representing the color angle on the color wheel (0 is red, 120 is green, 240 is blue).
- Saturation: a percentage (0% to 100%) showing how intense or pure the color is (0% is gray, 100% is full color).
- Lightness: a percentage (0% to 100%) showing how light or dark the color is (0% is black, 50% is normal, 100% is white).
css
color: hsl(120, 100%, 50%);
Example
This example shows how to use hsl() to set the background color and text color of a webpage. It uses a green color with full saturation and medium lightness.
css
body {
background-color: hsl(120, 100%, 50%);
color: hsl(0, 0%, 100%);
font-family: Arial, sans-serif;
padding: 2rem;
}
h1 {
color: hsl(240, 100%, 70%);
}Output
A webpage with a bright green background, white main text, and a light blue heading.
Common Pitfalls
Common mistakes when using hsl() include:
- Forgetting to add the
%sign for saturation and lightness values, which must be percentages. - Using hue values outside the 0-360 range (though CSS will wrap values, it can be confusing).
- Mixing up saturation and lightness, which changes the color drastically.
Here is a wrong and right example:
css
/* Wrong: missing % signs */ color: hsl(200, 50, 50); /* Right: with % signs */ color: hsl(200, 50%, 50%);
Quick Reference
Remember these tips when using hsl():
- Hue is an angle from 0 to 360 degrees.
- Saturation and lightness are percentages and need the
%sign. - Use
hsl()for easier color adjustments compared to hex or rgb. - You can add alpha transparency with
hsla()orhsl()with a fourth value.
Key Takeaways
Use
hsl(hue, saturation%, lightness%) to define colors by hue angle and percentages.Always include the % sign for saturation and lightness values.
Hue is a number from 0 to 360 representing the color wheel position.
Use
hsl() for flexible and intuitive color control in CSS.Add transparency with
hsla() or hsl() with alpha value.