Where to set base font?

4thSpace picture 4thSpace · May 28, 2013 · Viewed 9k times · Source

If I set a font-size on the body element, will that size also be 1em?

In other words, if I do:

body {
    font-family: Arial;
    font-size: 16px;
}

Can I be sure everywhere I use 1em it will equal 16px?

If the above is not the correct way, how else should I set a base font?

Sorry if base font is not the correct term. I’m not sure what this technique is referred to as. I believe it is similar a reset stylesheet, which overrides the browser's default styles.

Answer

David Storey picture David Storey · May 28, 2013

What you are looking to achieve can be done with the rem unit.

An em unit is “Equal to the computed value of the ‘font-size’ property of the element on which it is used.” In your case 1em would be 16px on the body element. But, if you change the font-size on any element, 1em on that element will equal the font-size of that element. If you use ems on font-size, it is relative to the font-size of the parent element. Thus if p was the child of div, and font-size on div was 12px, then font-size: 1em on p would be 12px.

On the other hand, a 1rem is always equal to the computed value of the font-size of the root element. In HTML this is the html element. Thus the size is always consistent. See http://www.w3.org/TR/css3-values/#rem-unit