J K
J K

Reputation: 5383

converting pixels to ems for margins and padding

I have a margin that should be 20px. How do I convert that to ems? The font size on the element is 1.08em. 1 em = 13px.

I thought dividing 30 by 13 would work, but that doesn't seem to.

Here's the CSS:

.test {
   margin-bottom: 30px;
   font-size: 1.23em;
}

I need to convert the 30px to ems.

Upvotes: 1

Views: 1604

Answers (3)

raduken
raduken

Reputation: 2119

I have a golden rule what I use in most of my projects it's quite easy and simple.

most of the browsers has 16px by standart, so I define my body and html 100% so the calculation can be easy.

sample:

    //Golden Rule:  
    //100% = 16px  browsers default
    //21px ÷ 16px = 1.5em


html,
body {
    width: 100%;
    height: 100%;
    min-height: 100%;
    color:#565a5c;
    font: normal normal 100%/1.5em "MyriadPro", "FontAwesome";
    padding-top: 50px;
    padding-bottom: 20px;

}

more sample:

h1 {
  font-size: 2em; /* 32px ÷ 16px */
  line-height: 1.3125em; /* 42px ÷ 32px */
  margin-bottom: .5em; /* 16px ÷ 32px */
}

h2 {
  font-weight: 400;
  font-size: 1.75em; /* 28px ÷ 16px */
  line-height: 1.285714286em; /* 36px ÷ 28px */
  color: $hc;
  margin-bottom: .785714286em; /* 22px ÷ 28px */
}

30px will be = 1.875em

I hope this helped you.

Upvotes: 1

CZorio
CZorio

Reputation: 483

Set body, html font size to 62.5% and then 16px=1em. The math becomes easy to work with at that ratio.

Here is an explanation on why. Css 62.5% why do developers use it?

Upvotes: 1

user3684918
user3684918

Reputation: 33

I think you're on the right track. Ems are calculated by multiplying your em value by the inherited font size of current element. If I understand correctly, the font size of the element right now is 14.04px, right? (13px X 1.08).

Using that same logic, you would divide 20px (your target margin) by the base font size (13px), which will give you 1.538... You can round up to 1.54em and you'll get 20.02px.

Does that work?

Upvotes: 0

Related Questions