Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS Basics (2014) The Box Model Margins

Em's/Padding/Margins/Font Size

Hi Guys,

I have a quick question about the concepts learned in the em section and the concepts here.

From what I have learned em's are relative to a parent's font size.

Ex:

.header-nav li { margin-right: 20px; margin-top: 60px; padding: 10px;

   /*margin-right: 1.25em;
      margin-top: 3.75em;   /* WHY ARE THESE NOT EQUAL TO PIXEL?
      padding: 0.5%;  */  

    font-size: 1.56em;  /* 25px */

Why aren't my em's for margin and padding right? For example for the margin-right - I want it to be 20px so I did 20 divided by 16. Should I have done 20 divided by the font size which is now equal to 25px?

Sorry if my question is confusing. Im confused too haha. Thanks

Dan Weru
Dan Weru
47,649 Points

Hello, dividing 20 by 16 is the right way to go about it. For it to work, the font of the context of the element/parent has to be 16px.

2 Answers

Dan Weru
Dan Weru
47,649 Points

The em value is calculated relative to the element's font-size. To ensure that the code works like you want it to, you have two choices.

Option 1

Set the font-size of the element to 16px. Then divide 20 by 16 to obtain the value of margin-right, 60 by 16 for margin-top, and 10 by 16 for padding. Following this option, your code should be:

.header-nav li{
   font-size: 1em;
   margin-right: 1.25em;
   margin-top: 3.75em;
   padding: 0.625em;
}

OR

Option 2

Assuming you really want the .header-nav li element to have a font-size of 1.56em (25px), divide 20 by 25 to obtain the value of margin-right, 60 by 25 for margin-top, and 10 by 25 for padding. Following this option, your code should be:

.header-nav li{
  font-size: 1.56em;
  margin-right: 0.8em;
  margin-top: 2.4em;
  padding: 0.4em;
 }

The font-size will not always be 16px, it could be more or less, depending on how you set it.

I tried option 2 and it worked. Thank you for helping me with calculations! Is there a way to figure out percentages?

Dan Weru
Dan Weru
47,649 Points

To figure out the percentages, just multiply the em values with 100%. For example 0.8em would become 80%. To convert your pixels to ems, take (pixel value divide by element’s font-size). For more info check this detailed explanation