px vs rem vs em

New to the dev world but during the last few weeks of learning I'm noticing a few different sizing options. I've done my fair share of research but just trying to see what the general public thinks. How do you choose which sizing options to use between px, rem and em. I keep seeing a lot of content saying stay away from px still cant understand why. If you guys have any resource I can use to learn a little more that would be great for my journey or any insights thanks in advance
6 Replies
snxxwyy
snxxwyy10mo ago
they're all used for similar things but work in different ways: - px is used to hard code values for elements, the reason why it is recommended to stray from it is because it collides with responsive design - em and rem are very similar, they both look at font sizes. em is based on the parent's font size and rem is based on the root font size (either defined or the default browser font-size). em is typically used for padding and margins and rem is used for font-sizes. The reason you don't use em for font-sizes is because of value stacking.
dellannie
dellannie10mo ago
thank you for this. This helps me a ton
snxxwyy
snxxwyy10mo ago
yeah for sure, no worries
snxxwyy
snxxwyy10mo ago
here's a quick example i whipped up of what i mean by value stacking, i also explain why to use rem for font sizes too. The comments in the css explain what is happening and why so if you get a bit confused you can refer to those. https://codepen.io/deerCabin/pen/mdadeLa
R
CodePen
unit examples
...
13eck
13eck10mo ago
My basic rules are: * rem is the same "size" no matter where you use it, so it's a constant—but it also respects any changes the user makes to the browser default. Because of this I use it for font sizing * em is variable based on the current font size: bigger font means bigger em. Because of this, I use it for spacing (margin, width, height, padding, etc) * px is a set measurement regardless of anything the user does, wants, or chooses. Because of this I only use it for display purposes: border width, border radius, and other such visual-flourishes. You can use it for max-width/height on an image as you know what the image dimensions are, but I find a max-width: 100% is going to be better 76% of the time (and allows you to use variable images based on the size of the screen)
dellannie
dellannie10mo ago
Thanks