How to Write a Hex Color in CSS
A hex color is a # followed by hexadecimal digits: two for red, two for green and two for blue, as in #0f6cbd. Three digits are the short form, and eight add transparency.
Syntax
#<red><green><blue>
#<red><green><blue><alpha>
| Part | What it does |
|---|---|
# | Starts a hex color. It's required. |
<red>, <green>, <blue> | How much of each color, from 00, none, to ff, the most, in hexadecimal: the digits 0 to 9 and the letters a to f. With one digit each, the digit is doubled: #06c is #0066cc. |
<alpha> | Optional. How opaque the color is, from 00, fully transparent, to ff, fully opaque. |
MDN's hex-color page lists the four forms: three, four, six and eight digits.
The Example
The example is three blue bars with white text, each colored with a different form: six digits, three digits and eight digits.
Step 1: Write the Code
Create a file named index.html in a text editor, such as Visual Studio Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hex colors</title>
<style>
p {
color: #ffffff;
}
.six {
background: #0f6cbd;
}
.three {
background: #06c;
}
.eight {
background: #0f6cbd80;
}
</style>
</head>
<body>
<p class="six">#0f6cbd</p>
<p class="three">#06c</p>
<p class="eight">#0f6cbd80</p>
</body>
</html>
Step 2: Open It in a Browser
Double-click index.html. It opens in your browser:

The screenshot comes from Chromium 159, the open-source browser that Chrome is built on.
What Happened
#0f6cbdbecamergb(15, 108, 189):0fis 15 in hexadecimal,6cis 108 andbdis 189.#06cbecamergb(0, 102, 204), the same as#0066cc: each digit was doubled.#0f6cbd80becamergba(15, 108, 189, 0.5): the same blue, half transparent, so the white page shows through and the bar looks pale.80is 128, about half of 255.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out the #: color: 0f6cbd | The value is invalid and ignored: the text stayed black | Start with # |
Using five digits: #0f6cb | Only three, four, six or eight digits are valid, so the value was ignored and the text stayed black | Use one of the four lengths |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| The color doesn't apply | The # is missing, or the code has the wrong number of digits | Check both |
| The color looks paler than expected | The code has eight digits, and the last two make it transparent | Use six digits for a solid color |
FAQ
Do uppercase letters work?
Yes. #0F6CBD gave the same rgb(15, 108, 189). MDN's page says the syntax is case-insensitive.
What does a four-digit hex color do?
It's the short form with transparency: #06c8 gave rgba(0, 102, 204, 0.533), the color of #06c at about half opacity.
Conclusion
Write hex colors with a # and three, four, six or eight digits. Six digits give a solid color, and eight add transparency.
Additional Resources
- hex-color, on MDN.
