Px or % for divs

I am builidng a simple website, I have usually used px to set the height and widths of my divs, but I have noticed on here it is much better to use % especially as people are using so many different sized screens now.

I have set the widths of my divs using %, but come a bit unstuck when it comes to the heights, am I still best using px opposed to % as they will contain images, text etc

Thanks in advance

Avoid setting heights at all. Setting heights on elements is usually asking for trouble. You need to let them find their own height based on the content within them. If, for example, you set a px height on a div with text inside it, that text might spill out of the container if the user increases font sizes.

Setting % heights has its own issues, as it if fairly “non intuitive”. What is that height based on? % of what? (It’s not the viewport height in most cases.)

Anyhow, don’t forget ems. I prefer setting most measurements in ems these days.

As Ralph said a percentage height can only be used if a parent of that element has a fixed height. If the parent has no height specified then the percentage height reverts to auto. You can’t base height on a child if the parent has min-height either as that will also default to auto. You can’t base percentage height on a parent where the height is only maintained by its content (as that can’t be resolved easily).

The only way you can use percentage height on an element is if all parents have height defined.

If elements are not nested and html,body are set to height:100% you can set a percentage height on an element but imagine if that elements is some distance from the top of the page (because other content is above), then if you apply 100% height it will gain the full 100% from the viewport and stretch miles below the fold.

Suffice to say percentages heights are rarely (if ever used).

Use px (for image containers) or ems where you have fixed height content but never use px for the height of text containers as that won’t allow zooming. For content that holds text then don’t use any height at all (as Ralph suggests) or indeed just use a min-height rule if you need some initial height.

If you are setting height just to make things equal then you are probably doing it wrong and you should be using other methods (such as display:table-cell).