CSS Colors
Learn to use various color formats to add vibrant and consistent styles to your web pages.
Defining Colors in CSS
Colors are a fundamental part of web design, and CSS provides several ways to specify them. You can set the color of text, backgrounds, borders, and more using different color formats, each with its own advantages.
🎨 Key Concept
CSS supports many color formats, including human-readable keywords, precise hexadecimal
codes, and versatile functions like rgb()
and hsl()
.
Color Keywords
The simplest way to specify a color is by using a predefined keyword. CSS provides over 140 named colors. This is easy to read but offers less flexibility than other methods.
/* Styles the paragraph with a keyword color */ p { color: tomato; }
Hexadecimal (Hex) Values
A hex value is a six-digit code that represents a color by defining the amount of red, green,
and blue. Each pair of digits (from 00
to FF
) represents a color
channel. Hex codes are widely used for their precision and compact format.
/* Hexadecimal values for colors */ .primary-box { background-color: #4facfe; } .secondary-box { background-color: #764ba2; }
RGB and RGBA Values
The rgb()
function defines a color using the intensity of red, green, and blue
light, each with a value from 0 to 255. The rgba()
function adds an alpha channel,
which controls the color's transparency. The alpha value ranges from 0.0 (fully transparent) to
1.0 (fully opaque).
/* Using RGB and RGBA functions */ .solid-red { background-color: rgb(255, 0, 0); } .transparent-blue { background-color: rgba(0, 0, 255, 0.5); }
HSL and HSLA Values
The hsl()
function defines a color using Hue, Saturation, and Lightness. This model
is often more intuitive for humans, as it's easier to adjust the hue or lightness without
changing the entire color. Like RGB, hsla()
adds an alpha channel for transparency.
- Hue: A degree on the color wheel from 0 to 360 (e.g., 0=red, 120=green, 240=blue).
- Saturation: A percentage from 0% (shades of gray) to 100% (full color).
- Lightness: A percentage from 0% (black) to 100% (white).
/* Using HSL and HSLA functions */ .vibrant-green { background-color: hsl(120, 100%, 50%); } .soft-blue { background-color: hsla(240, 50%, 75%, 0.7); }