Beginner · CSS basics · topic 17 of 64 · 25 min
Colours, backgrounds and units
Explanation
Ways to write a colour
| Format | Example | Note |
|---|---|---|
| Name | tomato, navy | About 140 names; quick for testing |
| Hex | #1d4ed8, #fff | Red, green, blue in base 16; most common in design files |
| rgb() | rgb(29 78 216) | Red, green, blue from 0 to 255 |
| rgb with alpha | rgb(0 0 0 / 50%) | Alpha means transparency: 0% clear, 100% solid |
| hsl() | hsl(220 80% 50%) | Hue (0-360), saturation, lightness: easy to make lighter or darker shades |
Modern browsers also support oklch(), a newer format where equal steps look equally bright to the eye. You will see it in design systems; hex and hsl are enough to start.
Backgrounds, borders and shadows
.banner {
background-color: #fff7ed;
background-image: linear-gradient(90deg, #f97316, #facc15);
border: 1px solid #fdba74;
border-radius: 12px; /* rounded corners */
box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
color: #1f2937;
}Units for size
| Unit | Relative to | Good for |
|---|---|---|
| px | Nothing (fixed) | Borders, small fixed details |
| rem | The root font size (usually 16px) | Font sizes, spacing |
| em | The current element's font size | Padding that grows with the text of a button |
| % | The parent | Widths inside a container |
| vw / vh | 1% of the viewport width / height | Full-screen sections |
| dvh | 1% of the dynamic viewport height | Full-height sections on phones where the address bar hides and shows |
Why rem for text? Many people, especially older users, increase the default text size in their phone or browser settings. Sizes in rem grow with that setting; sizes in px do not.
html { font-size: 100%; } /* respect the user setting (usually 16px) */
h1 { font-size: 2rem; } /* 32px by default */
p { font-size: 1rem; }
.hero { min-height: 100dvh; }Watch the lesson
Colours, backgrounds and units · 1/6
Colours can be names, hex codes, rgb or hsl.
Prefer a video by a teacher? Find free videos on “css colors units rem em px explained” on YouTube ↗
In real life: A UPI payment success screen
A payment success screen uses a green background in hsl so the designer can make a lighter shade for the card just by raising the lightness. The amount is 2.5rem so it grows when the user has big-text settings, and the screen uses min-height: 100dvh so the "Done" button is never hidden behind the phone's address bar.
Practice (0/2 done)
Style the .badge: background-color #16a34a, text colour white, border-radius 8px, and font-size 0.875rem.
Write a function pxToRem(px) that converts pixels to rem, assuming 1rem = 16px, and returns a string like "1.5rem". pxToRem(24) returns "1.5rem"; pxToRem(16) returns "1rem".
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.