James
James

Reputation: 1706

How to correctly work out briefed px to em with body and html preset sizes

I am doing a coding test for a potential job and want to get the calculations correct and wondering if someone knows of a tool online i can use to convert the pixel sizes requested in the brief based on the framework body and html sizes its using...

Defaults im using:

html {
    font-size: 62.5%
}
body {
    font-size: 1.5em;
    line-height: 1.6;
    font-weight: 400;
    font-family: HelveticaNeue, "Helvetica Neue", Helvetica, Arial, sans-serif;
    color: #222
}

I think using em's is much cleaner and a better way of setting font sizes etc... as then have mentioned what sizes i need to use for a few things in pixels but not sure how i can convert the requests PX into EM's based on the above im setting in the framework.

Fonts sizes:

So for example i wanted to create the heading

h1 {
  font-size: 1.8em; /* for example: but the correct em what would relate to 21px */
}

I found this useful tool: http://pxtoem.com/ - however know sure it would calculate correctly as only allows you to select size for body but think the 62.5% set in HTML would be adjusting the set body size at 62.5% correct?

Upvotes: 0

Views: 612

Answers (1)

James
James

Reputation: 1706

I have done some calculations and worked out for this to be the best solution for defining sets and converting them easily for anyone that this answer might help.

CSS Base:

html {
    font-size: 62.5%; /* 1rem = 10px on default browser settings (16px) */
}
body {
    font-size: 16px; /* setting PX unit for browsers that dont support rem below */
    font-size: 1.6rem; /* default to be used, browsers that dont support REM will use PX above */
    line-height: 1.5;
    font-family: sans-serif; /* used current font-family used on live website */
    color: #283533;
}

The em unit is relative to the font-size of the parent, which causes the compounding issue. The rem unit is relative to the root—or the html—element. That means that we can define a single font size on the html element and define all rem units to be a percentage of that.

I am in this case defining a base font-size of 62.5% to have the convenience of sizing rems in a way that is similar to using px.

As you will notice i have defined both px and rem in this example

font-size: 16px; font-size: 1.6rem;

But why? well it's a fall-back for any older browsers that don't support rem but this method, the conversions are a lot easier to work with as i am sure you will agree... example:

  • 8px = 0.8rem;
  • 10px = 1rem;
  • 14px = 1.4rem;
  • 26px = 2.6rem;

Hope this is a great answer for anyone else wanting to accurately work with such sizing conversions

Upvotes: 1

Related Questions