CSS basics

How to Set Text Color in HTML and CSS

Learn the reliable ways to set readable text colors with CSS, including Hex, RGB, HSL, custom properties and accessible fallbacks.

Published Β·Updated

CSS controls text color through the color property. The clearest pattern is to apply color to a semantic selector and let child elements inherit it.

body {
  color: #1f2937;
}

.notice {
  color: rgb(185 28 28);
}

Hex and RGB are both dependable for exact sRGB values. HSL is convenient when a design system adjusts hue, saturation or lightness. Convert an existing RGB token with the RGB to Hex converter, then keep one canonical format in your codebase.

Use custom properties for a system

Repeated literal values make global changes difficult. Name colors by role rather than appearance:

:root {
  --text-primary: #111827;
  --text-muted: #4b5563;
  --text-danger: #b91c1c;
}

.error-message { color: var(--text-danger); }

Role names survive a redesign better than names such as dark-gray. They also make dark-mode overrides straightforward.

Keep text readable

Color alone should not carry important meaning, and every foreground/background pair needs sufficient contrast. WCAG AA requires at least 4.5:1 for normal text and 3:1 for large text. Test the actual pair in the color contrast checker rather than judging it by eye.

For a strong, calm text color, explore navy color values. For errors and urgent labels, compare the red shade scale, selecting a shade that passes on the intended surface.

Next, learn how foreground choices interact with CSS background colors.

Continue reading