Question

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.

Was it helpful?

Solution

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

OTHER TIPS

If you set the font-size for an element, then (assuming your CSS rule will be applied) the em unit has that value for that element.

You cannot change the meaning of em from what it means in CSS: it denotes the font size of the element for which it is used (except when used in a font-size declaration or in a font shorthand, where it denotes the font size of the parent element).

Setting em to a fixed value would defeat the very purpose of the unit: it is meant to vary by context and settings. If you would want to set em to 16px, then just use the px unit instead of the em unit. If you think the numbers get too big then, you can use the pc (pica) unit: by CSS3 Units, and in browser practice, 1pc = 12pt = 16px.

When defining the font-size property, an em is equal to the size of the font that applies to the parent of the element in question. If you haven't set the font size anywhere on the page, then it is the browser default, which is probably 16px.

So, by default 1em = 16px, and 2em = 32px. If you set a font-size of 20px on the body element, then 1em = 20px and 2em = 40px.

Note that the value 2 is essentially a multiplier of the current em size.

Reference Link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top