Explore the different ways to define colors in CSS and learn how to apply background colors, images, and gradients to elements.
CSS supports several ways to define colors:
Named colors — CSS includes 147 named colors like red, tomato, steelblue, and rebeccapurple. They are easy to read but limited in precision.
Hexadecimal — A six-character code preceded by #. Each pair represents red, green, and blue: #FF5733. You can also use a three-character shorthand when both digits of each pair are the same: #F00 is the same as #FF0000.
RGB — Defines color using red, green, and blue values from 0 to 255: rgb(255, 87, 51). You can add an alpha channel for transparency: rgb(255, 87, 51, 0.5).
HSL — Defines color using hue (0-360), saturation (0%-100%), and lightness (0%-100%): hsl(14, 100%, 60%). HSL is often more intuitive for creating color variations because you can adjust lightness or saturation independently.
All of these methods produce the same result — they are just different ways to describe the same color.
<style>
.card {
background-color: #1a1a2e;
color: #e0e0e0;
padding: 24px;
margin: 12px 0;
border-radius: 8px;
}
.card-accent {
background-color: hsl(220, 80%, 55%);
color: white;
padding: 24px;
margin: 12px 0;
border-radius: 8px;
}
.faded {
background-color: rgb(255, 99, 71, 0.3);
padding: 16px;
border-radius: 8px;
}
</style>
<div class="card">Dark card with hex colors</div>
<div class="card-accent">Accent card with HSL color</div>
<div class="faded">Faded card with transparent RGB</div>Beyond background-color, CSS provides several properties for controlling element backgrounds:
background-color — Sets a solid background color. Accepts any color value.
background-image — Sets an image or gradient as the background. Use url() for images or gradient functions:
background-image: url('photo.jpg');
background-image: linear-gradient(to right, #667eea, #764ba2);background-size — Controls how the background image is sized: cover (fills the entire area), contain (fits entirely within the area), or specific dimensions.
background-position — Sets the starting position of a background image: center, top right, or exact values like 50% 50%.
opacity — Controls the transparency of an entire element (including its content) from 0 (fully transparent) to 1 (fully opaque). Unlike rgba() or hsla() which affect only a color, opacity affects everything inside the element.
What color format does hsl(0, 100%, 50%) represent?