Understanding CSS Units: px, rem, and em

Sidra Maqbool - May 30 - - Dev Community

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 */
}
Enter fullscreen mode Exit fullscreen mode

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 */
}

Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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 like rem and em helps your design stay consistent and adaptable to different screen sizes and user preferences.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player