CSS Colors
CSS Colors
CSS colors are used to set the color of text, backgrounds, borders, and other elements. CSS supports several color formats, giving you flexibility in how colors are defined.
The most commonly used color formats are color names, RGB, HEX, and HSL.
Color Names
CSS supports predefined color names such as red, blue, and black. Color names are easy to read but offer limited control.
p {
color: red;
}
div {
background-color: lightgray;
}
RGB Colors
RGB stands for Red, Green, and Blue. Each value ranges from 0 to 255 and defines the intensity of the color.
h1 {
color: rgb(255, 0, 0);
}
p {
color: rgb(34, 139, 34);
}
You can also use RGBA to add transparency:
.box {
background-color: rgba(0, 0, 255, 0.2);
}
HEX Colors
HEX colors use hexadecimal values to define colors. They start with a # followed by six digits.
h1 {
color: #ff0000;
}
p {
color: #228b22;
}
Short HEX notation can be used when values repeat:
.box {
background-color: #ccc;
}
HSL Colors
HSL stands for Hue, Saturation, and Lightness. This format is often easier for humans to understand and adjust.
- Hue: color type (0–360)
- Saturation: color intensity (0%–100%)
- Lightness: brightness (0%–100%)
h1 {
color: hsl(210, 100%, 50%);
}
.box {
background-color: hsl(120, 60%, 70%);
}
HSLA adds transparency support:
.overlay {
background-color: hsla(0, 0%, 0%, 0.5);
}
Which Color Format Should You Use?
- Use color names for quick demos
- Use RGB / RGBA when working with transparency
- Use HEX for consistency and design tools
- Use HSL / HSLA when adjusting brightness or saturation
Code Challenge
Goal: Style the elements below using different color formats.
HTML:
<div class="card"> <h2>Colors</h2> <p>CSS makes coloring easy.</p> </div>
Task:
- Set the heading color using HEX
- Set the paragraph color using RGB
- Give the card a light background using HSL
Try a Solution:
h2 {
color: #1f4bd8;
}
p {
color: rgb(60, 60, 60);
}
.card {
background-color: hsl(210, 60%, 95%);
padding: 16px;
border-radius: 10px;
}
What’s Next?
Next, you will learn how to work with background colors and background images in CSS.