3 ms·
>What is the benefit of em/rem? They (em*) scale with the element's font size, and if you set an elements font-size itself in em, that will be relative to the
by chmod775 6y ago
>What is the benefit of em/rem?
They (em*) scale with the element's font size, and if you set an elements font-size itself in em, that will be relative to the parent element's font size.
For example:
body { font-size: 18px }
.something { border: 0.1em solid black; }
.something > .inner { font-size: 1.5em }
If you change the font-size on body, everything on that page will re-scale seamlessly. This is most useful for things like buttons/icons that are supposed to flow properly with text. So now even if you use them once in big text, and once in a small footnote, they'll still fit perfectly within the line.
The biggest limitation to this approach is that you can easily end up with computed values that are weird fractions of pixels, so you have to be a bit smart and pick an easily divisible number for your base font-size if you're aiming for something pixel-perfect.
- onion2k 6y agoThe challenge with em units is that if you modify a parent element's size it changes the children as well. In your example, if you put 'font-size: 2.0em' on the .something class then the .inner would end up changing to 3.0em. That's rarely what you actually want to happen (especially in a web app). If you just want to control the overall font scaling of everything on the page using rem is preferable, because then they'd ignore the parent and scale based on the root element size.
- bbx 6y agoThe key is to use rem for font-size and em or unitless for all other properties: padding, border-width, margin, line-height. That way the size of the element is independent of the context.
- continuational 6y agoOk, I can kinda see the value of that - e.g. if you put a "tag button" inside some text, it will have the right size in relation to that text.