Sub topic 5
Hex codes: writing RGB in base 16
This chapter assumes you already know that a screen colour is three channel values (red, green, blue), each from 0 to 255 in 8-bit colour. It also assumes you are comfortable with base-10 arithmetic. Some CSS or JavaScript helps for the code examples but is optional. Here you will learn how hex codes encode those three numbers, how to read them by eye, which shorthand and extended forms exist, and which mistakes to avoid when converting.
What a hex code is
A hex code is a way of writing an RGB colour as a short string of base-16 digits. Base 16 (hexadecimal) uses sixteen symbols: 0 to 9 for the values zero to nine, and a to f for ten to fifteen. Letter case does not matter, so #FF8800 and #ff8800 are the same colour.
An 8-bit channel holds a value from 0 to 255, which is 256 possible values. Two hex digits also give 16 × 16 = 256 combinations. This is why hex works well for colour: one channel is always exactly two digits, and a full colour is exactly six digits after a # sign.
| Channel value (decimal) | Hex | Meaning |
|---|---|---|
| 0 | 00 | channel off |
| 16 | 10 | one full "sixteen" in the left digit |
| 128 | 80 | about half intensity (as a stored number) |
| 255 | ff | channel at maximum |
The first digit of a pair is the sixteens place and the second is the ones place. So 88 is 8 × 16 + 8 = 136, and ff is 15 × 16 + 15 = 255.
Reading a six-digit code
Split the six digits into three pairs, in the order red, green, blue.
The code #ff8800 is therefore rgb(255 136 0): red at full, green a little over half, blue off. That mix is a strong orange. With practice you can estimate a colour from the codes alone:
- Equal pairs, such as
#808080, give a grey. Higher values are lighter. #000000is black and#ffffffis white.- A large pair with two small ones points to that primary:
#e01010is a red. - Two large pairs with one small one give a secondary colour such as yellow (
#ffff00) or cyan (#00ffff).
The first pair is the most significant for the overall hue only when it is much larger than the others. Do not assume the first pair "dominates" in general. In #10ff10 the green pair decides the look.
The same colour in CSS
CSS accepts hex and functional notation interchangeably. The following rule uses three spellings of related values.
.button {
background-color: #ff8800;
border-color: rgb(255 136 0);
color: #fff;
}The background and border are the same orange. The text colour #fff is shorthand for #ffffff, covered next.
Shorthand and extended forms
CSS defines four hex lengths after the #.
| Length | Form | Example | Expands to |
|---|---|---|---|
| 3 digits | `#rgb` | `#f80` | `#ff8800` |
| 4 digits | `#rgba` | `#f80c` | `#ff8800cc` |
| 6 digits | `#rrggbb` | `#ff8800` | itself |
| 8 digits | `#rrggbbaa` | `#ff8800cc` | itself |
How the three-digit shorthand works
Each digit is doubled, not padded with a zero. So #f80 becomes #ff8800, because f becomes ff, 8 becomes 88 and 0 becomes 00. A common error is to read #f80 as #f08000. That is wrong.
The doubling rule means shorthand can only express colours whose pairs are repeated digits (00, 11, 22, up to ff). That is 16 values per channel, not 256. The colour #ff8801 has no shorthand, and #ff8800 does only because each pair repeats a digit.
The alpha channel
Four-digit and eight-digit codes add a fourth channel, alpha, which is opacity. The alpha pair works like the colour pairs: 00 is fully transparent and ff is fully opaque. The value cc is 12 × 16 + 12 = 204, so the opacity is 204 / 255, which is 80%.
Alpha is written last in CSS hex (#rrggbbaa). Some other tools, notably Android's #AARRGGBB colour format, put alpha first. Confirm the order in each tool's documentation. Swapping the two is a common source of wrong colours when moving values between a web project and an Android resource file.
Converting by hand
To convert a decimal channel to hex, divide by 16. The quotient is the first digit and the remainder is the second.
- Take 200. 200 ÷ 16 = 12 remainder 8.
- Map 12 to its letter:
c. The remainder 8 stays8. - The hex pair is
c8.
To go back, multiply the first digit by 16 and add the second: c8 = 12 × 16 + 8 = 200.
Memorise the letters: a = 10, b = 11, c = 12, d = 13, e = 14, f = 15.
Converting in code
The JavaScript functions below do the same work with built-in base-16 parsing and formatting. parseInt(h, 16) reads a hex string, and toString(16) writes one. The padStart(2, "0") call is essential, because toString(16) of 0 gives "0", not "00".
function hexToRgb(hex) {
const m = /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
if (!m) throw new Error("Invalid hex colour: " + hex);
return m.slice(1).map((h) => parseInt(h, 16));
}
function rgbToHex(r, g, b) {
return "#" + [r, g, b].map((v) => v.toString(16).padStart(2, "0")).join("");
}
console.log(hexToRgb("#ff8800")); // [255, 136, 0]
console.log(rgbToHex(255, 136, 0)); // "#ff8800"The regular expression accepts an optional #, requires exactly six hex digits, and ignores case through the i flag. It rejects shorthand and alpha forms. If your tool must accept those, expand them first.
function expandHex(hex) {
let h = hex.replace(/^#/, "");
if (h.length === 3 || h.length === 4) {
h = h.split("").map((c) => c + c).join("");
}
return "#" + h.toLowerCase();
}
console.log(expandHex("#f80")); // "#ff8800"
console.log(expandHex("#f80c")); // "#ff8800cc"Edge cases and common errors
Out-of-range channel values
rgbToHex(300, 0, 0) produces "#12c00", which is five digits and not a valid colour, because 300 is 12c in hex. Validate that each channel is an integer from 0 to 255 before formatting. If your values come from calculations, round and clamp them first.
function clampChannel(v) {
return Math.min(255, Math.max(0, Math.round(v)));
}
console.log(clampChannel(300)); // 255
console.log(clampChannel(127.6)); // 128Missing padding
Without padStart, a channel of 5 becomes "5" instead of "05". The string #ff85 00 collapses, shifting every pair after it. The result is a wrong colour or an invalid one. The code #ff8800 could become #ff880 if the last channel is 0, which a browser will ignore.
Dropping or misplacing the hash
CSS requires the #. Many design tools show codes without it, and some APIs expect it absent. A function like hexToRgb above handles both. Know which form your destination wants.
Invalid digits
Only 0-9 and a-f are valid. The letter O is not zero, and g through z do not exist in hex. A code such as #ff88oo is invalid. Browsers silently drop the whole declaration, so the element falls back to its previous colour. This failure gives no error message, which makes it easy to miss.
Precision is fixed at 8 bits
Hex stores exactly 256 levels per channel. It cannot represent a value between two steps, and it cannot express colours outside the sRGB range that the chapter on colour spaces covers. When a design tool converts from a wider space, the hex code is already a rounded approximation.
Hex is not linear light
Doubling a hex value does not double the light the screen emits. The value #808080 is about 22% of the light of #ffffff, not 50%, because sRGB uses a non-linear encoding. The hex code is a stored number, and later chapters explain the encoding.
Choosing hex or functional notation
Hex and rgb() carry identical information for opaque sRGB colours. The choice is about readability and tooling.
| Situation | Better choice | Reason |
|---|---|---|
| Design tokens, brand palettes, hand-off between tools | Hex | Compact, copy-pasteable, widely supported |
| Calculating or animating a channel in code | `rgb()` or numbers | No parsing needed |
| Needing to read channel values at a glance | `rgb()` | Decimal values are easier to compare |
| Opacity that changes often | `rgb()` with alpha, or 8-digit hex | Both work; decimal alpha is easier to edit |
Hex has one more practical benefit. A six-digit code is a single token, so it is easy to search for in a codebase and to compare in a diff.
Mini-check: reading codes at a glance
Take #1a9e55. Split it into 1a, 9e and 55. Then 1a = 1 × 16 + 10 = 26, 9e = 9 × 16 + 14 = 158, and 55 = 5 × 16 + 5 = 85. The colour is rgb(26 158 85): low red, high green, medium blue, which is a mid green. You can make this estimate before converting anything, just by noticing that the middle pair is the largest.
Exercise
Convert #2b7fd4 to decimal RGB values, then write the three-digit shorthand if one exists. If none exists, say why.
Show answer
The pairs are 2b, 7f and d4. 2b = 2 × 16 + 11 = 43. 7f = 7 × 16 + 15 = 127. d4 = 13 × 16 + 4 = 212. The colour is rgb(43 127 212). No shorthand exists because shorthand needs each pair to repeat one digit (such as 22 or 77), and 2b, 7f and d4 do not.
Exercise
A function calls rgbToHex(10, 0, 255) but its toString(16) step has no padding. What string results, and what is the correct one?
Show answer
Without padding, 10 becomes "a", 0 becomes "0" and 255 becomes "ff", so the result is "#a0ff" (four digits, which CSS reads as the shorthand #rgba and so as a different, translucent colour). With padStart(2, "0") the result is "#0a00ff".
Exercise
What opacity does the code #ff880080 describe, and why is it not exactly 50%?
Show answer
The alpha pair is 80, which is 8 × 16 = 128. Opacity is 128 / 255, about 50.2%. It is not exactly 50% because 255 is odd, so no whole-number alpha equals one half.