🌱BeginnerCSS Colors and Backgrounds
CSS Colors
Master the four ways to express color in CSS: named colors, hex codes, RGB, and HSL.
Overview
Color is one of the most fundamental aspects of CSS. You can apply color to text, backgrounds, borders, shadows, and more. CSS supports four primary color formats:
**Named colors** 140+ predefined names like `red`, `navy`, `tomato`, `cornflowerblue`. Simple and readable but limited.
**Hex codes** A six-character hexadecimal value like `#ff5733`. The first two digits are red, the next two green, the last two blue. Very common in design tools.
**RGB / RGBA** `rgb(255, 87, 51)` uses three numbers 0–255 for red, green, and blue. `rgba()` adds an alpha (opacity) channel: 0 is fully transparent, 1 is fully opaque.
**HSL / HSLA** `hsl(14, 100%, 60%)` uses hue (0–360°), saturation (%), and lightness (%). HSL is the most intuitive for designers: you can easily create tints and shades by changing lightness.
Modern CSS also supports the `color-mix()` function and wide-gamut color spaces, but for beginners the four formats above cover all practical needs.
Key Points
- •color sets the foreground (text) color; background-color sets the background
- •Named colors: 140+ names red, blue, coral, slategray, etc.
- •Hex: #RRGGBB #000000 is black, #ffffff is white, #ff0000 is red
- •Shorthand hex: #rgb #f00 = #ff0000, #ccc = #cccccc
- •RGB: rgb(red, green, blue) each value 0–255
- •RGBA: rgba(r, g, b, alpha) alpha 0 (transparent) to 1 (opaque)
- •HSL: hsl(hue, saturation%, lightness%) intuitive for color relationships
Examples
Color formats comparison
/* All four produce the same tomato-red color */
.named { color: tomato; }
.hex { color: #ff6347; }
.rgb { color: rgb(255, 99, 71); }
.hsl { color: hsl(9, 100%, 64%); }Using alpha transparency
/* Semi-transparent overlay */
.overlay {
background-color: rgba(0, 0, 0, 0.5); /* 50% transparent black */
}
/* Using HSLA */
.badge {
background-color: hsla(220, 90%, 56%, 0.8); /* 80% opaque blue */
}rgba() and hsla() are widely used for overlays, tooltips, and ghost buttons.
Practical color properties
.button {
color: white; /* text color */
background-color: #2563eb; /* background */
border-color: #1d4ed8; /* border */
box-shadow: 0 2px 4px rgba(0,0,0,0.2); /* shadow */
}Common Mistakes
- Forgetting that #rgb shorthand doubles each digit: #f3a = #ff33aa not #f003a0
- Using rgb() values above 255 or below 0 browsers clamp them but it shows a mistake
- Confusing "color" (text) with "background-color" (fill)
Note
For building a consistent color system, use HSL. Vary only the lightness to get tints and shades of the same hue: hsl(220, 90%, 90%) is a light blue, hsl(220, 90%, 30%) is a dark blue.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4