ANSI Foreground vs Background Color Codes Explained
Understand the difference between ANSI foreground (text) and background color codes. Learn the SGR code ranges for standard colors (30-37, 40-47) and bright colors (90-97, 100-107).
Detailed Explanation
Foreground vs Background Colors in ANSI
ANSI escape sequences distinguish between foreground (text) color and background color using different SGR parameter ranges. Understanding this distinction is fundamental to working with terminal colors.
Foreground Color Codes
Foreground codes set the color of the text characters themselves:
- Standard foreground: 30-37 (Black through White)
- Bright foreground: 90-97 (Bright Black through Bright White)
- 256-color foreground:
38;5;Nwhere N is 0-255 - True color foreground:
38;2;R;G;Bfor any RGB value
Background Color Codes
Background codes set the color behind the text:
- Standard background: 40-47 (Black through White)
- Bright background: 100-107 (Bright Black through Bright White)
- 256-color background:
48;5;Nwhere N is 0-255 - True color background:
48;2;R;G;Bfor any RGB value
Combining Foreground and Background
You can set both in a single escape sequence by separating codes with semicolons:
# White text on red background
echo -e "\033[37;41mWhite on Red\033[0m"
# Bright cyan text on dark blue background
echo -e "\033[96;44mCyan on Blue\033[0m"
# 256-color: Orange text on dark gray background
echo -e "\033[38;5;208;48;5;236mOrange on Gray\033[0m"
Reset Codes
39resets only the foreground to the default color49resets only the background to the default color0resets both foreground and background plus all formatting
Pattern Recognition
The offset between foreground and background codes is always 10: foreground 31 (red) corresponds to background 41 (red), foreground 92 (bright green) corresponds to background 102 (bright green). This consistent pattern makes it easy to remember the codes.
Use Case
Understanding foreground vs background colors is critical when designing readable terminal output. You need to ensure sufficient contrast between text and background colors for accessibility. This knowledge is essential for creating colored table headers, highlighted search results, status bars, and menu selections in terminal applications.