How To Use em In CSS
Answers (2)
Add AnswerIn CSS, an em unit is equal to the computed font-size
for the element to which the em is applied. When em units are declared on child elements that don’t have a font-size
defined, they will inherit their font-size
from their parent, or from another ancestor element, possibly going all the way back to the root element on the document.
Look at the following CSS:
.example { font-size: 20px; }
In this case, 1em on this element, or on its child elements (assuming no other font-size
definitions), would be equal to 20px. So if we added a line:
.example { font-size: 20px; border-radius: .5em; }
This border-radius
value of .5em
computes to 10px (i.e. 20*.5). Similarly:
.example { font-size: 20px; border-radius: .5em; padding: 2em; }
The padding value of 2em
is equal to 40px (20*2). As mentioned, this type of calculation would apply to any child elements as well — unless any of those child elements had an explicitly defined font-size
value, in which case the em value would be calculated based on that. If no font size is defined anywhere in the CSS, the em unit will be equal to the browser’s default font size for the document, which is usually 16px.