This forum is now read-only. Please use our new forums at

CSS: An Overview Forum

View Course » View Exercise

746 points
Submitted by
about 4 years ago

When do use %, px, and ems

Hi, I have a question.

When adjusting the div's width and height, I know using px is the standard, but it appears different for different people with different screens.

So in further exercises, the code uses %, which I am not really sure what it means. I assume that by setting width: 97% means the div will span the 97% of the screen. But does it work with height? I tried that, and it does not seem to work well. Why is it the case?

Furthermore, is it more advisable to use ems in the future?


1 vote


You can set the height of an element to a percent, but only if the parent element has a specific height set. In order to best accomplish this, you should set the height of the body to 100% in a style tag or css file:

html, body {
    height: 100%;

    <div style='height: 35%'></div>

As for percent vs em: sizes and distances of fonts and elements can be defined using either % or em. They are both relative sizes, but how the actual size is determined is based on what you use:

% sets the width and height of an element based on the size of the parent. For example the inner div here is 200px wide:

<div style='width: 400px;'>
    <div style='width: 50%'></div>

This div is 45% of the user's screen size:

    <div style='width:45%'></div>

em is defined based on the amount of space an "m" takes in the font size of the parent. Let's say you have your font sent to 12px (or 9pt). This div will be wide enough to hold 5 letter m's:

<div style='width: 5em;'></div>

Neither % nor em is better. It all depends on how you want your webpage to behave. A good discussion can be found here:

609 points
Submitted by
Scott Korin
about 4 years ago


0beec889fe9f2b5dff3d001c7b2b8891?s=140&d=retro Scott Korin about 4 years ago

Note that in general, using em is preferred if you want to try to use one layout for both traditional desktop/laptop as well as smaller device such as tablets or smartphones.

51958746dcb210c039000127_454761227 Chrissy52 about 4 years ago

Thanks for this, very informative - I didn't realise the em was the size of an 'm' that makes me smile for some reason :)