In CSS, the em unit is a relative measurement based on the font size of the parent element. It is often used to make elements scale proportionally.
Why use ems?
- Flexibility: Designs can adapt to different font sizes, making them more accessible for users with varying preferences or visual impairments.
- Maintainability: Changing a base font size will cascade changes throughout the entire document, making it easier to adjust overall typography.
- Responsiveness:
ems can help create more responsive designs, as elements can scale relative to each other.
How to use ems?
Set a base font size
Typically, you’ll set a base font size on the <html> element. This becomes the reference point for all other em values in your document.
html {
font-size: 16px;
}
Use ems for font sizes
- Direct child: If an element is a direct child of the
<html>element, 1em is equal to 16px (or whatever base font size you’ve set). - Nested elements: For nested elements, 1em is equal to the font size of its parent element.
body {
font-size: 1em; /* Inherits from html */
}
h1 {
font-size: 2em; /* Twice the size of the body */
}
p {
font-size: 1.2em; /* 120% of the body's font size */
}
Example
<!DOCTYPE html>
<html>
<head>
<style>
html {
font-size: 16px;
}
body {
font-size: 1em;
}
h1 {
font-size: 2em;
}
p {
font-size: 1.2em;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph with a slightly larger font size than the body.</p>
</body>
</html>
Benefits and Drawbacks
Benefits:
- Flexibility: Easy to adjust font sizes globally.
- Maintainability: Changes to one element can affect many others.
- Accessibility: Supports users with different font size preferences.
Drawbacks:
- Complexity: Can make CSS more complex for beginners.
- Calculations: Requires some mental math to determine exact pixel sizes.
When to use ems?
- Font sizes: The most common use case.
- Margins and paddings: Create relative spacing based on font size.
- Other properties: Can be used for width, height, and line-height.
Additional considerations
remunit: Similar toem, but relative to the root element (html).- Other units:
px,%, vw,vh, etc., each with its own use cases.
In conclusion, the em unit provides a flexible and maintainable way to define font sizes and other dimensions in CSS. By understanding its relationship to the parent element’s font size, you can create more scalable and accessible designs.