RGB to HEX Color Conversion: A Complete Guide
Understanding color formats in web development. Learn how to convert between RGB, HEX, HSV, HSL, and CMYK color spaces with practical examples.
RGB to HEX Color Conversion: A Complete Guide
Color representation is fundamental to web development and design. Understanding different color formats and how to convert between them is an essential skill. This comprehensive guide covers everything you need to know about RGB, HEX, and other color spaces.
Understanding Color Models
RGB Color Model
RGB stands for Red, Green, Blue. It's an additive color model where colors are created by combining different intensities of red, green, and blue light.
Format: rgb(red, green, blue)
- Each component ranges from 0 to 255
- Total possible colors: 256 × 256 × 256 = 16,777,216
Examples:
rgb(255, 0, 0) /* Pure red */
rgb(0, 255, 0) /* Pure green */
rgb(0, 0, 255) /* Pure blue */
rgb(255, 255, 255) /* White */
rgb(0, 0, 0) /* Black */
rgb(128, 128, 128) /* Gray */
HEX Color Model
HEX (hexadecimal) is a compact representation of RGB colors using base-16 notation.
Format: #RRGGBB or #RGB
- Each component uses two hexadecimal digits (00-FF)
- Can be shortened to 3 digits when each pair is identical
Examples:
#FF0000 /* Red (can be shortened to #F00) */
#00FF00 /* Green (can be shortened to #0F0) */
#0000FF /* Blue (can be shortened to #00F) */
#FFFFFF /* White (can be shortened to #FFF) */
#000000 /* Black (can be shortened to #000) */
Converting RGB to HEX
Manual Conversion
Each RGB component (0-255) needs to be converted to hexadecimal (00-FF):
Step-by-step example: rgb(220, 100, 50)
- Red: 220 ÷ 16 = 13 remainder 12 → D (13) C (12) → DC
- Green: 100 ÷ 16 = 6 remainder 4 → 64
- Blue: 50 ÷ 16 = 3 remainder 2 → 32
Result: #DC6432
Quick Reference Table
| Decimal | Hex | Decimal | Hex | Decimal | Hex |
|---|---|---|---|---|---|
| 0 | 00 | 85 | 55 | 170 | AA |
| 15 | 0F | 100 | 64 | 185 | B9 |
| 30 | 1E | 115 | 73 | 200 | C8 |
| 45 | 2D | 130 | 82 | 215 | D7 |
| 60 | 3C | 145 | 91 | 230 | E6 |
| 75 | 4B | 160 | A0 | 255 | FF |
JavaScript Conversion
function rgbToHex(r, g, b) {
// Ensure values are within 0-255
r = Math.max(0, Math.min(255, r));
g = Math.max(0, Math.min(255, g));
b = Math.max(0, Math.min(255, b));
// Convert to hex and pad with zeros
const toHex = (n) => {
const hex = n.toString(16);
return hex.length === 1 ? '0' + hex : hex;
};
return `#${toHex(r)}${toHex(g)}${toHex(b)}`.toUpperCase();
}
// Usage
console.log(rgbToHex(220, 100, 50)); // #DC6432
console.log(rgbToHex(255, 255, 255)); // #FFFFFF
Alternative One-Liner
const rgbToHex = (r, g, b) =>
'#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('');
Converting HEX to RGB
JavaScript Conversion
function hexToRgb(hex) {
// Remove # if present
hex = hex.replace(/^#/, '');
// Expand shorthand (e.g., "03F" to "0033FF")
if (hex.length === 3) {
hex = hex.split('').map(char => char + char).join('');
}
// Parse hex values
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
return { r, g, b };
}
// Usage
console.log(hexToRgb('#DC6432')); // { r: 220, g: 100, b: 50 }
console.log(hexToRgb('#FFF')); // { r: 255, g: 255, b: 255 }
Regex-Based Conversion
function hexToRgb(hex) {
const result = /^#?([a-fd]{2})([a-fd]{2})([a-fd]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
Other Color Formats
HSL (Hue, Saturation, Lightness)
HSL is often more intuitive for designers:
hsl(0, 100%, 50%) /* Red */
hsl(120, 100%, 50%) /* Green */
hsl(240, 100%, 50%) /* Blue */
hsl(0, 0%, 50%) /* Gray */
RGB to HSL Conversion:
function rgbToHsl(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0; // achromatic
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
case g: h = ((b - r) / d + 2) / 6; break;
case b: h = ((r - g) / d + 4) / 6; break;
}
}
return {
h: Math.round(h * 360),
s: Math.round(s * 100),
l: Math.round(l * 100)
};
}
HSV/HSB (Hue, Saturation, Value/Brightness)
function rgbToHsv(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const d = max - min;
let h, s = max === 0 ? 0 : d / max;
const v = max;
if (max === min) {
h = 0;
} else {
switch (max) {
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
case g: h = ((b - r) / d + 2) / 6; break;
case b: h = ((r - g) / d + 4) / 6; break;
}
}
return {
h: Math.round(h * 360),
s: Math.round(s * 100),
v: Math.round(v * 100)
};
}
RGBA and HEXA (with Alpha Channel)
Add transparency:
/* RGBA */
rgba(255, 0, 0, 0.5) /* 50% transparent red */
/* HEX with alpha (8 digits) */
#FF000080 /* 50% transparent red */
function rgbaToHexa(r, g, b, a) {
const toHex = (n) => {
const hex = Math.round(n).toString(16);
return hex.length === 1 ? '0' + hex : hex;
};
return `#${toHex(r)}${toHex(g)}${toHex(b)}${toHex(a * 255)}`;
}
console.log(rgbaToHexa(255, 0, 0, 0.5)); // #FF000080
Practical Applications
1. Dynamic Theme Generation
function generateColorPalette(baseHex) {
const rgb = hexToRgb(baseHex);
const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
return {
base: baseHex,
lighter: hslToHex(hsl.h, hsl.s, Math.min(hsl.l + 20, 100)),
darker: hslToHex(hsl.h, hsl.s, Math.max(hsl.l - 20, 0)),
complementary: hslToHex((hsl.h + 180) % 360, hsl.s, hsl.l),
triadic: [
hslToHex((hsl.h + 120) % 360, hsl.s, hsl.l),
hslToHex((hsl.h + 240) % 360, hsl.s, hsl.l)
]
};
}
2. Color Contrast Checker
function getContrastRatio(hex1, hex2) {
const getLuminance = (hex) => {
const rgb = hexToRgb(hex);
const [r, g, b] = [rgb.r, rgb.g, rgb.b].map(val => {
val /= 255;
return val <= 0.03928
? val / 12.92
: Math.pow((val + 0.055) / 1.055, 2.4);
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
};
const lum1 = getLuminance(hex1);
const lum2 = getLuminance(hex2);
const brightest = Math.max(lum1, lum2);
const darkest = Math.min(lum1, lum2);
return (brightest + 0.05) / (darkest + 0.05);
}
// WCAG requires 4.5:1 for normal text, 3:1 for large text
const ratio = getContrastRatio('#000000', '#FFFFFF');
console.log(ratio); // 21 (excellent contrast)
3. Color Picker Component
class ColorPicker {
constructor(initialColor = '#000000') {
this.color = initialColor;
}
setRGB(r, g, b) {
this.color = rgbToHex(r, g, b);
return this;
}
setHex(hex) {
this.color = hex;
return this;
}
getRGB() {
return hexToRgb(this.color);
}
getHSL() {
const rgb = this.getRGB();
return rgbToHsl(rgb.r, rgb.g, rgb.b);
}
lighten(percent) {
const hsl = this.getHSL();
hsl.l = Math.min(100, hsl.l + percent);
this.color = hslToHex(hsl.h, hsl.s, hsl.l);
return this;
}
darken(percent) {
return this.lighten(-percent);
}
}
// Usage
const picker = new ColorPicker('#3498db');
picker.lighten(20);
console.log(picker.color); // Lighter shade of blue
Performance Considerations
Caching Conversions
const colorCache = new Map();
function cachedRgbToHex(r, g, b) {
const key = `${r},${g},${b}`;
if (colorCache.has(key)) {
return colorCache.get(key);
}
const hex = rgbToHex(r, g, b);
colorCache.set(key, hex);
return hex;
}
Batch Processing
function batchConvert(colors) {
return colors.map(color => {
if (color.startsWith('#')) {
return hexToRgb(color);
} else {
const match = color.match(/rgb((d+),s*(d+),s*(d+))/);
if (match) {
return rgbToHex(
parseInt(match[1]),
parseInt(match[2]),
parseInt(match[3])
);
}
}
});
}
Browser Compatibility
All major browsers support RGB and HEX colors. However, be aware of:
- RGBA: IE9+
- 8-digit HEX (with alpha): Modern browsers only
- HSL/HSLA: IE9+
- Named colors: All browsers (140 named colors)
Common Color Schemes
Material Design Colors
const materialColors = {
red: '#F44336',
pink: '#E91E63',
purple: '#9C27B0',
deepPurple: '#673AB7',
indigo: '#3F51B5',
blue: '#2196F3',
lightBlue: '#03A9F4',
cyan: '#00BCD4',
teal: '#009688',
green: '#4CAF50'
};
Tailwind CSS Colors
const tailwindBlue = {
50: '#eff6ff',
100: '#dbeafe',
200: '#bfdbfe',
300: '#93c5fd',
400: '#60a5fa',
500: '#3b82f6',
600: '#2563eb',
700: '#1d4ed8',
800: '#1e40af',
900: '#1e3a8a'
};
Tools and Resources
Use our free color conversion tools:
Conclusion
Understanding color conversion is essential for web development. Key points to remember:
- RGB uses decimal (0-255), HEX uses hexadecimal (00-FF)
- Always validate color values before conversion
- Use HSL for more intuitive color manipulation
- Consider accessibility with contrast ratios
- Cache conversions for better performance
Master these techniques and you'll have full control over colors in your applications!