Colors & Backgrounds
Learn how to set text colors, background colors, and background images using CSS. Colors are specified using named colors, hex codes, RGB, RGBA, and HSL formats. Backgrounds can be solid colors, gradients, or images.
Color Formats
- Named colors — red, blue, green, coral, tomato. CSS supports 147 named colors
- Hex — #ff0000 (red), #00ff00 (green), #0000ff (blue). 6-digit or 3-digit shorthand (#f00)
- RGB — rgb(255, 0, 0). Red, green, blue values from 0-255
- RGBA — rgba(255, 0, 0, 0.5). Adds alpha channel for transparency (0-1)
- HSL — hsl(0, 100%, 50%). Hue (0-360°), Saturation (0-100%), Lightness (0-100%)
- color property — Sets the text color of an element
- background-color — Sets the background color of an element
Colors Example
<!DOCTYPE html>
<html>
<head>
<style>
.box1 { background-color: #04AA6D; color: white; padding: 15px; margin: 5px; }
.box2 { background-color: rgb(231, 76, 60); color: white; padding: 15px; margin: 5px; }
.box3 { background-color: rgba(52, 152, 219, 0.5); padding: 15px; margin: 5px; }
.box4 { background-color: hsl(39, 100%, 50%); color: #333; padding: 15px; margin: 5px; }
</style>
</head>
<body>
<div class="box1">Hex: #04AA6D</div>
<div class="box2">RGB: rgb(231, 76, 60)</div>
<div class="box3">RGBA with 50% opacity</div>
<div class="box4">HSL: hsl(39, 100%, 50%)</div>
</body>
</html>Tip
Stick to hex codes (#667eea) or HSL for most projects — they are the most readable in code. Use RGBA when you need transparency (e.g., overlay backgrounds). HSL is the best for creating color palettes because you can change lightness while keeping the same hue.
CSS variables enable theming and dark mode without preprocessors
Common Mistake
Using 'color' when you mean 'background-color' (and vice versa). Remember: 'color' sets the TEXT color only. 'background-color' sets the BACKGROUND of the element. This is the most common beginner color mistake.
Practice Task
Create a color palette card: (1) Make a div with background-color using each format — hex, rgb, rgba, and hsl. (2) Set the text color to white with 'color'. (3) Add padding: 15px to each box. Try adjusting the alpha value in rgba to see transparency change.
Quick Quiz
Key Takeaways
- Learn how to set text colors, background colors, and background images using CSS.
- Named colors — red, blue, green, coral, tomato. CSS supports 147 named colors
- Hex — #ff0000 (red), #00ff00 (green), #0000ff (blue). 6-digit or 3-digit shorthand (#f00)
- RGB — rgb(255, 0, 0). Red, green, blue values from 0-255