In CSS (Cascading Style Sheets), colors are used to style various elements of a webpage. There are several ways to define colors in CSS, including:
- Named Colors
- Hexadecimal Colors
- RGB Colors
- RGBA Colors
- HSL Colors
- HSLA Colors
Named Colors
CSS supports 140 named colors that you can use directly. Examples include red
, blue
, green
, etc.
<style> body { background-color: lightblue; } h1 { color: darkred; } </style> <h1>Welcome to My Styled Page</h1> <p>This page has a light blue background and a dark red heading.</p>
Hexadecimal Colors
Hexadecimal colors are defined with a #
followed by either three or six hexadecimal digits.
- Three-digit hexadecimal:
#RGB
- Six-digit hexadecimal:
#RRGGBB
<style> body { background-color: #add8e6; /* lightblue */ } h1 { color: #8b0000; /* darkred */ } </style> <h1>Welcome to My Styled Page</h1> <p>This page has a light blue background and a dark red heading.</p>
RGB Colors
RGB colors are defined using the rgb()
function, which takes three values (red, green, and blue) ranging from 0 to 255.
<style> body { background-color: rgb(173, 216, 230); /* lightblue */ } h1 { color: rgb(139, 0, 0); /* darkred */ } </style> <h1>Welcome to My Styled Page</h1> <p>This page has a light blue background and a dark red heading.</p>
RGBA Colors
RGBA colors are similar to RGB but include an alpha channel to define opacity. The alpha value ranges from 0 (completely transparent) to 1 (completely opaque).
<style> body { background-color: rgba(173, 216, 230, 0.5); /* lightblue with 50% opacity */ } h1 { color: rgba(139, 0, 0, 0.7); /* darkred with 70% opacity */ } </style> <h1>Welcome to My Styled Page</h1> <p>This page has a light blue background and a dark red heading.</p>
HSL Colors
HSL stands for Hue, Saturation, and Lightness. Hue is an angle from 0 to 360 degrees, saturation and lightness are percentages.
<style> body { background-color: hsl(195, 53%, 79%); /* lightblue */ } h1 { color: hsl(0, 100%, 27%); /* darkred */ } </style> <h1>Welcome to My Styled Page</h1> <p>This page has a light blue background and a dark red heading.</p>
HSLA Colors
HSLA is similar to HSL but includes an alpha channel for opacity.
body { background-color: hsla(195, 53%, 79%, 0.5); /* lightblue with 50% opacity */ } h1 { color: hsla(0, 100%, 27%, 0.7); /* darkred with 70% opacity */ }
These different ways of defining colors in CSS provide flexibility and a wide range of options for styling your web pages.