Is it good practise to use "em" unit for "almost" everything ? What about CVA then ?

Imagine card component, that could be reused in 3 different places (2 different parts of UI and 1 mobile view). To make this really re-usable I put almost everything (except borders) in "em" unit. Thats way if I am reusing it in different parts of app all I need to make smaller/bigger component is just to put parent font size. Seems like quiet comfortable but on the other hand a lot of libraries are using CVA instead. For button sm/md/lg. Is it bad practise what am I doing ?
4 Replies
Wouter Schaap
Wouter Schaap12mo ago
The difficulty with em is, it is based on inheritance of the font-size from the current or else parent elements. So you if someone accidentally sets a font-size on a couple nested elements which rely on it, it could have a sort of ripple effect. Also see: https://blog.logrocket.com/using-em-vs-rem-css/#problems-working-em-rem
Lawrence Eagles
LogRocket Blog
Using em vs. rem in CSS - LogRocket Blog
In this article, we will learn about both the em and rem relative length units, go over code examples, and learn when to use each of them.
interpod
interpod12mo ago
So i am wondering right now. CVA or container-query could solve such issues right?
croganm
croganm12mo ago
I mean if you truly understand the consequences of using em, it would be fine in my opinon. As mentioned though, could cause a ripple effect if not careful
Wouter Schaap
Wouter Schaap12mo ago
I agree with @croganm, if you fully understand em, it should not be an issue. What I have come to realize after working for multiple clients over the years, is that the general level of understanding of CSS of other devs that have to work on my code is usually less than my own. Which is fine, they tend to be better in other areas. However that means sometimes a clever workable solution poses a future risk if not fully understood. If code is meant for production, and sees other people working on it, I usually opt for a simpler, more spelled out solution, so chances are lowest hard to track errors are accidentally introduced later. Container queries together with rem values might be better in that case yes. I have no prior experience with CVA, can't advise you on that.