#CSS - % or px for width
10 messages · Page 1 of 1 (latest)
- Use % when you want the width to be relative to the parent (good for responsive layouts)
- Use px when you want a fixed size, no matter the screen or container
Rule:
% = flexible, px = fixed
@digital charm Thanks a lot!
em or rem is a better choice as a rule...
True, em/rem are ideal for font relative sizing and scalability, %/px still matter for layout structure though
I never ever use px unless I have a client looking for "pixel-perfect" compliance to a design (which is silly to begin with since different browsers render differently) or unless I have a really, really, REALLY good reason to do so.
% I occasionally use for very limited cases - like 100% or 50% - but if you ever see someone writing 23% for example then that's a "magic number" which has likely been arrived at by trial and error and it's an indication the the remainder of the layout is probably in some way incorrect...
There are some tricks that you can leverage (like the 62.5% trick) that allows you to code in virtual "pixels" for most cases but which also have all the advantages of rem (eg. users with visual impairments that use a font size other than default).
I would encourage you to begin using rem/em early so that it becomes second nature for you to do so and it will eventually save your bacon!
When using the newer min() function , you can use both !
width: min(100%, 10rem);
It take the smaller of the two values. So when 100% (based on the parents size) is smaller than 10rem, the width will use 100%; when 10rem is smaller then 100% of the parent, the width will use 10rem. Shorthand for
width:100%; max-width: 10rem;
These are example values, you could use px units or any other units. There is also a max() function which does the opposite, takes the larger of two values.
So overall, is it considered best practice to mostly use rem/em instead of px or %, correct? I'm still new to all of this, so I'm wondering if it's a good idea to kind of 'set aside' px and % for now. Just curious, since these units haven't been covered yet in the Scrimba course. Thanks a lot, everyone — super helpful!
% can be used if it's a "logical" case - eg. 50% for half the container but avoid weird magic numbers just to force a fit (e.g. 23%). Otherwise rem/em should be preferred.
One place where I do break this is for an ultra thin border - something like: border: 1px solid black
Use Percent (%) when:
You want elements to resize with their container (responsive design)
Working with fluid layouts that need to stretch or shrink
Inside Flexbox or Grid containers
Use Pixels (px) when:
You need exact, unchanging sizes (like icons or borders)
Working with fixed-width elements that shouldn't resize
Setting maximum/minimum size limits
Good practice:
Combine them - like a container at 90% width but with max-width: 1200px