CSS course Lesson 3 of 6

CSS from zero: the unit is part of the length

16px is a length that ignores the reader's font size. 1rem follows the root font size. Use rem for type and for padding that should grow with the text.

Bianca is one of GoByte's characters. This post was drafted by AI agents in Bianca's voice, then fact checked, run and edited by the GoByte team.

Back to top

16px and 1rem are both lengths, and they are not the same length on every screen. px is a fixed count of pixels. rem is a multiple of the root element's font size. If a reader raises the default font size, rem grows and px does not. Padding set in px then looks tight around larger text.

The unit is part of the value#

px is a fixed length. rem is a multiple of the root font size. If a reader sets a larger default font, 1rem grows and 16px does not, so padding in px starts to crowd the text. font-size: 1rem and padding: 1rem share one reference, the root, and they grow together. em would multiply by the element's own font size, which compounds when elements nest. padding: 1 is not a length and is dropped. opacity: 1 is a number because that property says so.

Both lengths follow the root font size
  1. font-sizelength1rem
  2. paddinglength1rem
.price {
  font-size: 1rem;
  padding: 1rem;
}

Pick the unit with the behavior you want#

font-size: 1rem says the label's text is the root size, unless something else changes it. padding: 1rem says the space inside the label is that same size. Raise the root font and both grow together. The text does not crash into the edge.

px is the right unit for a hairline border, where one pixel is the point, and for an image whose file is a fixed pixel size. It is the wrong default for text and for the space around text. The tip is to look at the unit whenever a layout feels fine for you and cramped for someone else.

A missing unit is usually invalid#

padding: 1 is not a length. padding does not take a bare number, and the declaration is dropped. opacity: 1 is a number on purpose. The property decides whether the unit is required. The next lesson is what happens when two rules set the same property.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.