The 'em' is a scalable unit that is used in web document media. An 'em' is equal to the current font-size, for instance, if the font-size of the document is 12pt, 1em is equal to 12pt. Ems are scalable in nature, so 2em would equal 24pt, .5em would equal 6pt, etc.
When it comes to CSS, the 'em' unit represents the size of a font in relation to the size of the parent element's font. This means the 'em' can change value relative to the context it is used in, providing a significant advantage in responsive web design.
Let's illustrate this with an example. If we set a style rule such as:
div {
font-size: 20px;
}
p {
font-size: 0.8em;
}
This means that the paragraph ('p') text size will be 80% of its parent div's font size. Since the font size of the div is defined as 20 pixels, the paragraph will have a font size of 16 pixels. So, with 'em', it became easier to scale the font size in a context-dependent manner.
When designing a responsive webpage, using relative units like 'em' can be beneficial. However, the 'em' unit can cause confusion sometimes because it cascades, meaning it can compound across nested elements unintentionally.
For example:
div {
font-size: 2em;
}
p {
font-size: 0.8em;
}
Here, if a 'p' (paragraph) tag is nested within a 'div', the paragraph's font size would be 80% of the div's computed '2em' value, which might not be what the designer expected. Therefore, while 'em' is helpful, it's always essential to understand the cascading nature and verify that it aligns with the desired design outcome.
Other relative units like 'rem' (relative to the root element) or 'vw' / 'vh' (relative to the viewport width / height) can be alternatives depending on your specific design scenario.