CSS CSS Basics 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?