For those of you working with relative font-sizes in your CSS, here is a basic equation for getting the exact size equivalent in ems, given a desired px value:
emr = pxt ÷ pxp, where
emr = result font size, in ems;
pxt = target font size, in px;
pxp = parent element’s font size, in px;
This equation allows you to work more easily with relative font sizes, since HTML elements translate 1em as whatever font size they inherit from their parent. To illustrate, if you had a parent div with a font size equivalent to 12px, and you wanted to set a child h3 to 21px:
emSize = 21px / 12px = 1.75em;
Notice how targeting a font size larger than the parent’s results in a value greater than 1em. Conversly, for smaller target sizes, you get a value of less than 1em. If you’re working with percentages, just multiply the number by 100, and change the unit to ‘%’:
pctr = pxt ÷ pxp × 100
Whenever possible, express your em values up to 3 decimal places to avoid slightly irregular line-heights caused by non-integer font-sizes.
Very nice tip! Thanks.
Here’s how I start all of my CSS files:
body {
font-size: 62.5%; /*Sets all fonts to 10px*/
}
Then all you have to do is use em’s to get exact pixel sizes. For example:
1.1em = 11px
1.5em = 15px
2em = 20px
This way makes it a little easier to quickly calculate font sizes.
Craig: I use it a lot, but the
62.5%trick is only good for children of the body element, and maybe descendant elements whosefont-sizes haven’t been explicitly set. Other elements will have to base their relativefont-sizeon the nearest ancestor whose size is not the equivalent of 10px, which is where the equation comes in handy.Nevertheless, the
62.5%reset is a perfect companion to the presented equation.This was a really handy post today. I am starting to use the 62.5% reset more often. Does it make a difference if it’s on the html element as opposed to the body? I wouldn’t think so…
Btw, what would not be a descendant of the body?
Diona Kidd: I don’t think there’s a difference whether you put it in
htmlorbody; I just use body because that’s where all the displayed content is located.thanks for the size tips. I always had a problem resizing my font size.