CSS · Unit 1: Styling basics · Lesson 5 of 5
Units: px, rem and %
px is a fixed size on screen.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
px is a fixed size on screen. rem is relative to the root font size, usually 16px, so 1.5rem is 24px, and it grows when someone chooses a bigger default text size.
% is relative to the parent: width: 50% is half the width of the container.
Use rem for font sizes so text respects people's settings, and px for small details like borders.
Worked example
CSS
.box {
width: 50%;
font-size: 1.25rem;
border: 2px solid teal;
}
The HTML it styles
<div class="box">Half-width box</div>
Key terms
- Units
- px is fixed, rem follows the root font size, % follows the parent. Only 0 needs no unit.
Practise it in Code Academy
It has 4 exercises (multiple choice, fill in the blank and write code from a prompt) and takes about 6 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.