How to pick which CSS unit to use in which circumstance. I wish this was an easy question to answer but it really is one of those depends type of questions but in this case . It does actually depend on something more than others.
So, In this article, we are going to generalize the above questions.
Note: There is always an exception to pretty much all of these rules these are just rules of thumb.
Are you declaring a font size ?
You probably want to go with rem they are relative units but in the case of rem, they are relative to the font size of the root element which is our HTML element most of the time that defaults to 16 px. rem are better than using pixels because they adapt to the user's system and browser preference whereas if you use pixels you going to locks things in and you can overwrite the user's preferences.
Are you declaring a width ?
This is one of the harder ones to answer because there are so many different things that you might be a width on but for the most part a percentage is a nice direction to go on often coupled with a max-width. There are times also where a viewport width might be a good unit to use but it can cause some trouble or some unintended consequences. Another unit that could be a really good fit is the ch unit
Are you declaring padding or margin ?
For the most part, going with either em or rem for these. It depends on whether you want the padding or margin to be consistent despite the element that you are setting it on or if you want it to adjust based on that element's font size.
Are you declaring a height ?
A percentage, rem, or viewport height all are a good fit.
Note: This is an incomplete article. Soon I am going to add more insight on it. If you are up for contribution please add your thought in the comment box.
Happy Learning ;)
Top comments (0)