0
0
CssConceptBeginner · 3 min read

What is rem in CSS: Explanation and Usage

rem in CSS is a unit of measurement that stands for "root em". It measures sizes relative to the root element's font size, usually the <html> element, making it easy to create scalable and consistent layouts.
⚙️

How It Works

The rem unit measures size based on the font size of the root HTML element, which is usually the <html> tag. Think of it like using a ruler that always starts from the same base size, no matter where you are in the page.

For example, if the root font size is 16 pixels, then 1rem equals 16 pixels. If you set an element's width to 2rem, it will be 32 pixels wide. This makes it easy to keep sizes consistent and scalable across your whole website.

Unlike em, which depends on the font size of the parent element, rem always refers back to the root, so it avoids unexpected size changes when elements are nested.

💻

Example

This example shows how rem units work by setting the root font size and using rem for padding and font size on a box.

css
html {
  font-size: 16px;
}

.box {
  width: 10rem;
  height: 5rem;
  background-color: #4CAF50;
  color: white;
  font-size: 1.5rem;
  padding: 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0.5rem;
}
Output
A green rectangular box 160px wide and 80px tall with white text sized 24px and padding 16px inside.
🎯

When to Use

Use rem when you want your design to scale easily by changing just one value: the root font size. This is great for responsive design, accessibility, and user preferences.

For example, if a user changes their browser's default font size for better readability, your site will adjust smoothly if you use rem units.

It's also helpful when you want consistent spacing and sizing across different components without worrying about nesting effects that happen with em.

Key Points

  • rem stands for "root em" and is based on the root font size.
  • It helps create consistent and scalable layouts.
  • Unlike em, it does not depend on parent elements.
  • Great for accessibility and responsive design.
  • Changing the root font size updates all rem-based sizes automatically.

Key Takeaways

rem units measure size relative to the root font size, usually the <html> element.
Using rem makes your design scalable and consistent across the whole page.
rem is better than em for avoiding unexpected size changes from nested elements.
It improves accessibility by respecting user font size preferences.
Adjusting the root font size changes all rem-based sizes automatically.