CSS em and rem units

441 viewsOtherTechnology

I’m dumb. I watched some videos on it and maybe it’s just the way they talk or the way they explain it, but I don’t fully get why to use em and rem units vs pixels.

Note: I do use tailwind and am happy I don’t really have to think about it 🙂 but without it I pretty much always use pixels instead lol.

In: Technology

2 Answers

Anonymous 0 Comments

I’m no dev, but after reading one page about it, it sounds pretty simple to me.
Pixels (px) is absolute, it will just use that regardless of any other settings.

rem, is a variable that starts with whats set in the root element. So 1rem = root element. So you base your sizing in rem units off of what the root element is, so its effectively a parent and child. If the root element size (in px) changes, so will your rem values, based on what they are. So if the root element value is 20px, 1rem is also 20px. If you change rem to .5, then that equates to 10px.
Its a way to keep a ‘master’ value that can be set at a top level, and have all your page values be relative to that.

em, is similar, but works under a single element. So rather than 1em equating to the root element of 20, its equal to the current element value.

Using them lets you keep a root value (that could be set in the browser by the user), and change your page relatively to that. Not an absolute change.

Anonymous 0 Comments

rem units are a bit easier to grasp and much more useful than px when dealing with zoom/scale on type.

The R in the name is _root_. Basically whatever the base size of the body is, that is a scale factor. So if you set font-size of the body to 10px, and the rem of some heading to 3.2rem, it will be like you set it to 32px.

Why do that? Because now your sizes will proportionately change if the user zooms the browser. Or if you have media queries changing the baseline size for screen width.

Em units are the worst. It’s like rem, but the relative baseline is the parent’s font size. So they compound as you nest elements and are hard to keep track of.