Colors are one of the most important parts of web design. CSS allows you to change the text color, background color, borders, and many other visual elements.
There are multiple ways to define colors in CSS.
1️⃣ Color Property
The most common property for changing text color is:
color: value;
Example:
p {
color: red;
}
This makes the paragraph text red.
2️⃣ Background Color
To set the background of an element:
background-color: value;
Example:
div {
background-color: lightblue;
}
3️⃣ Ways to Define Colors in CSS
Named Colors
CSS supports 147 predefined color names, like:
p {
color: navy;
}
div {
background-color: tomato;
}
Example colors: red, blue, green, orange, pink, purple, black, white.
Hexadecimal Colors
A hex color starts with # followed by 3 or 6 digits:
color: #RRGGBB;
Example:
p {
color: #ff0000; /* Red */
}
div {
background-color: #00ff00; /* Green */
}
Short-hand 3-digit hex is also possible:
color: #f00; /* Red */
RGB Colors
RGB stands for Red, Green, Blue. Values go from 0 to 255.
color: rgb(255, 0, 0); /* Red */ background-color: rgb(0, 128, 0); /* Green */
You can also use RGBA to add transparency:
color: rgba(255, 0, 0, 0.5); /* 50% transparent red */
HSL Colors
HSL stands for Hue, Saturation, Lightness.
color: hsl(0, 100%, 50%); /* Red */ color: hsl(120, 100%, 50%); /* Green */ color: hsl(240, 100%, 50%); /* Blue */
Hue = Color (0–360°)
Saturation = Intensity (0%–100%)
Lightness = Brightness (0% = black, 100% = white)
You can also add alpha with HSLA:
color: hsla(0, 100%, 50%, 0.3); /* 30% transparent red */
4️⃣ Applying Colors to Borders
div {
border: 3px solid #ff9900; /* Orange border */
}
<!DOCTYPE html>
<html>
<head>
<title>CSS Colors Example</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
color: #333333;
padding: 20px;
}
h1 {
color: navy;
}
h2 {
color: rgb(255, 0, 0); /* Red */
}
p {
color: hsl(120, 60%, 40%); /* Greenish */
background-color: rgba(255, 255, 0, 0.3); /* Semi-transparent yellow */
padding: 10px;
border: 2px solid #0000ff; /* Blue border */
}
.highlight {
background-color: tomato;
color: white;
padding: 5px;
}
</style>
</head>
<body>
<h1>Main Heading (Named Color)</h1>
<h2>Subheading (RGB Color)</h2>
<p>This paragraph uses HSL color for text and RGBA for background.</p>
<p class="highlight">This is a highlighted paragraph with a named color.</p>
</body>
</html>