CSS CSS Basics The Box Model Margins

Vanessa Clifton
Vanessa Clifton
1,349 Points

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,636 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,636 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.

Vanessa Clifton
Vanessa Clifton
1,349 Points

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,636 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