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.