CSS Colors
How to Define Colors in CSS
CSS allows you to style elements with color using different formats. You can apply colors to:
color
: text colorbackground-color
: background colorborder-color
,outline-color
, etc.
✅ Color Value Types
Format | Example | Description |
---|---|---|
Named Colors | red , blue , black | Simple color names |
HEX Codes | #ff0000 , #333 | Hexadecimal (6 or 3 digits) |
RGB | rgb(255, 0, 0) | Red, Green, Blue values (0–255) |
RGBA | rgba(255, 0, 0, 0.5) | RGB with alpha (transparency) |
HSL | hsl(0, 100%, 50%) | Hue, Saturation, Lightness |
HSLA | hsla(0, 100%, 50%, 0.5) | HSL with transparency |
transparent | Fully transparent | Special keyword |
currentColor | Inherits color value | Useful for consistent theming |
✏️ Example: Color on Text & Background
h1 {
color: #333; /* dark text */
background-color: rgba(255, 255, 0, 0.2); /* transparent yellow */
}
🌈 Example: Using HSL for Theming
:root {
--primary: hsl(220, 90%, 56%);
}
button {
background-color: var(--primary);
color: white;
}
🔥 Transparency with Alpha Channels
Use rgba()
or hsla()
to control transparency:
div {
background-color: rgba(0, 0, 0, 0.1); /* 10% black */
}
✅ Best Practices
- Use HEX or HSL for easier color palette control.
- Use CSS variables (
var()
) for reusable and theme-able colors. - Prefer RGBA or HSLA when you need transparency.
- Use
currentColor
to match text color with borders/icons/etc.