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

Arikaturika Tumojenko
Arikaturika Tumojenko
8,897 Points

How is the margin bottom calculated for the h2?

h2 {
  font-size: 3.3125em; /* 53px/16px -  where 16px is the size of the root element*/
  font-weight: normal;
  line-height: 1.1;
  margin-bottom: 0.5em; /* 26px  - where 26px is the desired value we want to set the margin to and we divide it by the font size which is 53px */
}

Based on this, what's the general formula we use when calculating margin for an element using ems? Why are we using the font size as a reference point and not the width of the element for example.

Wilson Usman
Wilson Usman
35,206 Points

I think if you read this, it will make more sense. I don't want to do a bad job at breaking it down.

Definition of em units: Relative to the font-size of the element (2em means 2 times the size of the current font)

The formula here is something like this:

h2 
font size = 53/16 (Desired h2 font-size/root font-size)
margin-bottom = 26/53 (Desired margin-bottom/font-size)

body {
    font-size: 16px; /* root font-size */
}
In this case, 1em on this element, or on its child elements (assuming no other font-size definitions), would be equal to 16px. So if we added a line:

h2 {
  font-size: 3.3125em; /* 53px/16px -  where 16px is the size of the root element*/
  font-weight: normal;
  line-height: 1.1;
  margin-bottom: 0.5em; /* 26px  - where 26px is the desired value we want to set the margin to and we divide it by the font size which is 53px */
}
This margin-bottom value of .5em computes to 26px ( i.e. 53 * .5)

1 Answer

Wilson Usman
Wilson Usman
35,206 Points

The short answer is em and % values are based off of the font-size. If you want to dig deeper, you might want to google something like understanding ems in css, I've read some good articles about this topic.

Hope this makes more sense now.

Arikaturika Tumojenko
Arikaturika Tumojenko
8,897 Points

So in this case we divided 53px to 36 px?