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

CSS: An Overview Forum

View Course » View Exercise

823 points
C8e355901a5ed885e78715ca2d5dd92c?s=140&d=retro
Submitted by
teraPlayer40968
over 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?

Thanks!


1 vote

permalink

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%;
}

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

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>
</div>

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

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

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: http://stackoverflow.com/questions/609517/why-em-instead-of-px

609 points
0beec889fe9f2b5dff3d001c7b2b8891?s=140&d=retro
Submitted by
Scott Korin
over 4 years ago

2 Comments

0beec889fe9f2b5dff3d001c7b2b8891?s=140&d=retro Scott Korin over 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 over 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 :)