In CSS, there are three common units used for sizing elements: px
, rem
, and em
. Each of these units serves a different purpose and understanding their differences can help you create more flexible and responsive designs.
1. rem (Root em)
rem
is a unit relative to the root element (<html>
). It scales based on the font size of the root element, making it particularly useful for creating responsive designs. One rem
is equal to the font size of the root element. For example:
html {
font-size: 16px;
}
h1 {
font-size: 2rem; /* 2 * 16px = 32px */
}
In this example, the font size of the <html>
tag is set to 16px, so 1rem
equals 16px. Therefore, 2rem
for the <h1>
element results in a font size of 32px.
2. em
em
is relative to the font size of its parent element. This makes it useful for creating scalable designs where elements adjust based on their container's size. For example:
.parent {
font-size: 16px;
}
.child {
font-size: 0.8em; /* 0.8 * 16px = 12.8px */
}
Here, the .child
element has a font size of 0.8 times the font size of its parent .parent
, resulting in a 12.8px font size if the parent has a font size of 16px.
3. px (Pixels)
px
is an absolute unit of measurement and is not relative to any other elements. It's often used for fixed-size elements where precise control over dimensions is required. For example:
.element {
font-size: 14px;
margin-top: 20px;
}
In this example, the font size of the .element
is set to a fixed 14 pixels and the top margin is set to 20 pixels.
Choosing the Right Unit
-
Use px
when you need fixed-size elements that won't change, such as borders or shadows. -
Use rem
for font sizes to ensure better accessibility for users who adjust their browser's default font size. rem is relative to the root font size. -
Use em
when you want sizes to be relative to their parent element, like buttons that need to adjust based on their container's size. Using relative units likerem
andem
helps your design stay consistent and adaptable to different screen sizes and user preferences.
Top comments (3)
As I point out in my blog post explaining the
px
:So in conclusion: It is usually better to go all the way only using px. If you only use px, you also know that the page scales well when zoomed, and thus working even better accessibility-wise.
Just to nit pick on a technical note. You write:
This is not entirely correct. When you use
em
to specify font-size,1em
represents the font-size of the parent element. But for all other uses ofem
, it refers to the current element! See for instance this example, where I set the height and with of a block to be1em
. :-)Great article! I didn't know the differences between those units from css.