Colors and Size Units
Ways to Express Colors
In CSS, colors can be expressed in several ways besides names.
| Format | Example | Characteristics |
|---|---|---|
| Color name | red, skyblue | Intuitive, but only a limited set of colors |
| HEX code | #ff0000 | Red, green and blue as two hexadecimal digits each (RRGGBB) |
| RGB | rgb(255, 0, 0) | Red, green and blue as numbers from 0 to 255 |
| RGBA | rgba(255, 0, 0, 0.5) | RGB plus opacity (alpha) |
How to read a HEX code: #ffffff splits into three pairs: ff (red) + ff (green) + ff (blue). A pair of 00 means none of that color, and ff means the maximum. #ffffff has all three colors at maximum, so it's white; #000000 has all of them at 0, so it's black.
Opacity (Alpha): the last number in rgba() is a value between 0 (fully transparent) and 1 (fully opaque). It's often used when you want only the background color to be slightly see-through.
Units for Expressing Size
| Unit | Meaning | Analogy |
|---|---|---|
px | A fixed number of pixels | An absolute length measured on paper with a ruler |
% | A ratio relative to the parent element | A relative length like "half the parent's size" |
em | A multiple of the parent's (or its own) font size | "How many times the current font size" |
rem | A multiple of the root (html) font size | A ruler based on the whole page |
px is easy to work with but never changes even when the screen size changes, while %/em/rem change size flexibly depending on the situation. When building responsive designs, you end up using relative units a lot.
Summary
| Concept | One-line summary |
|---|---|
| Color units | Expressed with HEX/RGB/RGBA; the alpha value even controls transparency |
| Size units | px is an absolute value; %/em/rem are relative values that change with their reference |
Reference: personal Notion study notes
