Reference article · Programming
Colour formats: HEX, RGB and HSL
CSS can express a colour through HEX, RGB or HSL. Choose a notation according to how you want to read or edit it. Legibility also depends on the background and contrast.
HEX and RGB
RGB expresses red, green and blue components, commonly from 0 to 255. HEX writes them in hexadecimal: ff is 255 and 00 is zero. #ff0000 and rgb(255 0 0) both mean red. The shorthand #f00 doubles each digit; not every six-digit colour has a shorthand equivalent.
HSL
HSL describes hue as an angle and saturation and lightness as percentages. hsl(0 100% 50%) means red. Lower saturation moves towards grey; changing lightness moves towards black or white.
Three notations for one colour
All three declarations mean red. In one rule, the last valid declaration for the property applies. Your final stylesheet only needs one.
.notice {
color: #ff0000;
color: rgb(255 0 0);
color: hsl(0 100% 50%);
}Alpha and transparency
Alpha controls opacity. rgb(255 0 0 / 50%) is translucent and depends on its background. #ff000080 gives approximately that opacity.
Readable text contrast
WCAG 2.2 criterion 1.4.3 requires at least 4.5:1 for normal text and 3:1 for large text, subject to its defined exceptions. HSL lightness is not the relative luminance used in that calculation. Check text against its actual background, including dark themes.
Practice
- Express blue in all three notations.
- Compare translucent colour over light and dark backgrounds.
- Measure contrast for real text rather than inferring it from appearance.
References
Related articles
- Fundamentals: variables, conditions and loops
- Semantic HTML and page structure
- CSS: box model, Flexbox and Grid
- JavaScript: functions, parameters and scope
- JavaScript: arrays, objects and data transformations
- DOM and events: connect JavaScript to HTML
- Promises, async/await and fetch requests
- HTTP and web APIs: requests, responses and status codes
- JSON: format, parsing and data validation
- Git: changes, commits, branches and remotes
- Node.js and npm: project scripts and dependencies
- Debugging and tests: finding and checking errors
- UUID identifiers
- Random values in JavaScript
