CSS Colors

ADVERTISEMENT

How to Define Colors in CSS

CSS allows you to style elements with color using different formats. You can apply colors to:

  • color: text color
  • background-color: background color
  • border-color, outline-color, etc.

✅ Color Value Types

FormatExampleDescription
Named Colorsred, blue, blackSimple color names
HEX Codes#ff0000, #333Hexadecimal (6 or 3 digits)
RGBrgb(255, 0, 0)Red, Green, Blue values (0–255)
RGBArgba(255, 0, 0, 0.5)RGB with alpha (transparency)
HSLhsl(0, 100%, 50%)Hue, Saturation, Lightness
HSLAhsla(0, 100%, 50%, 0.5)HSL with transparency
transparentFully transparentSpecial keyword
currentColorInherits color valueUseful 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.

ADVERTISEMENT