Hex color

2 snippets across 2 stacks - HTML & CSS, Regular Expressions

HCHTML & CSS

Color Formats

HC · Colors & Backgrounds
Syntax
color: #rrggbb | #rgb | rgb(r g b) | hsl(h s l) | oklch(L C H);
Example
.text-hex   { color: #1e293b; }
.text-rgb   { color: rgb(30 41 59); }
.text-hsl   { color: hsl(215 28% 17%); }
.text-oklch { color: oklch(0.35 0.05 260); }

/* With alpha (transparency) */
.overlay { background: rgb(0 0 0 / 0.5); }
.tint    { background: hsl(210 100% 50% / 0.1); }

Note Modern CSS uses space-separated values with a slash for alpha: rgb(255 0 0 / 0.5). The older comma syntax still works but is being phased out. oklch provides perceptually uniform colors, so adjusting lightness produces visually consistent results across hues.

RXRegular Expressions

Hex Color Code

RX · Common Patterns
Syntax
/^#(?:[0-9a-fA-F]{3}){1,2}$/
Example
JS:  /^#(?:[0-9a-fA-F]{3}){1,2}$/.test('#ff5733')   // true
JS:  /^#(?:[0-9a-fA-F]{3}){1,2}$/.test('#F3A')      // true
JS:  /^#(?:[0-9a-fA-F]{3}){1,2}$/.test('#xyz')      // false
Output
true (6-digit), true (3-digit shorthand), false (invalid hex)

Note Matches both 3-digit (#RGB) and 6-digit (#RRGGBB) hex colors. The {1,2} quantifier on the 3-char group handles both lengths. Does not cover 8-digit RGBA hex -- extend to {1,2,} won't work; add a separate alternation for #RRGGBBAA if needed.

Frequently asked questions

How does HTML & CSS handle hex color?
This task is covered in 2 stacks on this page: HTML & CSS, Regular Expressions. The "Color Formats" snippet in HTML & CSS uses `color: #rrggbb | #rgb | rgb(r g b) | hsl(h s l) | oklch(L C H);`.
Which code does the HTML & CSS example use?
The "Color Formats" snippet uses `color: #rrggbb | #rgb | rgb(r g b) | hsl(h s l) | oklch(L C H);`, from the Colors & Backgrounds section of the HTML & CSS cheat sheet.
Which stacks cover "hex color" on this page?
HTML & CSS, Regular Expressions. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Color Formats": Modern CSS uses space-separated values with a slash for alpha: rgb(255 0 0 / 0.5). The older comma syntax still works but is being phased out. oklch provides perceptually uniform colors, so adjusting lightness produces visually consistent results across hues.