I'm learning CSS and keep seeing rem used for typography and spacing. How does that help when someone changes their browser's font size, and how do you keep the layout from falling apart?
Why use rem for font sizes if bigger text might break the layout?
Answers
rem is relative to the root element's font size. If you leave that size flexible, it normally follows the browser's default font size. So 1.25rem will be 20px with a 16px default, but 25px with a 20px default.
That gives people who need larger text a way to get it without relying on zoom. Watch out for html { font-size: 16px }. That fixes the root size and can override the user's preferred default. Leaving it alone or using 100% avoids that problem.
Reply to this answer
The layout needs room to grow. Fixed heights on buttons, cards and headers are common trouble spots because the text gets larger but the box doesn't. Use padding or min-height where appropriate, and let text wrap.
Flexible grid or flex layouts help too. Test with longer labels and translated text, not just larger fonts. A layout that only works with one exact line of text is pretty fragile.
Reply to this answer
Test two different things: raise the default font size in browser settings, then separately try browser zoom. Normal page zoom also scales pixels, so it won't necessarily reveal the same problems as changing the default font size.
Some browsers also offer text-only zoom, which is another useful test because the surrounding layout may not scale the same way.
Reply to this answer
You don't need rem for everything. It's handy for type and spacing that should grow with the root font size. Pixels can be fine for details like borders and shadows. For line-height, a unitless value such as 1.5 scales with each element's own font size.
Reply to this answer
Add your answer
Answers are reviewed before publication.
8q+plovercrank_529:
So rem depends on the root size actually being allowed to change, not just on using the unit?
c.826+torvexa:
Right. A fixed root size means rem values still scale relative to each other, but they won't follow a changed browser default in the same way.