Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

What is Rem in CSS: How to Build Scalable Layouts

CSS offers developers many capabilities, including control of layouts, and length values of HTML elements necessary to create flexible and visually appealing web apps. This control through different units of measurement in CSS is crucial to scale elements’ properties. The most commonly used CSS units are pixelspercentagesem units, rem units, and viewport units (vhvwvmaxvmin).

In recent years, rem has become increasingly popular. It is flexible, relatively intuitive, and offers benefits crucial to responsiveness. The role of rem in responsive web design ensures consistent proportion across different screen sizes and devices. 

This article will explore rem units in-depth, how they work, their advantages over other CSS units, their application in web design, and the best practices guiding the use of rem in CSS. Alright, let’s go on a joy ride.

Exploring Rem in CSS: A Comprehensive Overview

The rem unit is a relative unit for measuring length in CSS. It stands for root em, based on the font-size property of the root element, the <html> element. By specifying the CSS unit for each element dimension as rem, these elements are scaled based on the font size of the root element. By default, most browsers font-size value is 16px, equal to 1rem:

.some-text {
  font-size: 1.5rem; /* 1.5rem equals 24px because of the 16px browser's default */
}

The rem unit offers several advantages, including scaling elements relative to the document, making it a preferred choice in modern CSS development. This ability of rem to scale elements ensures design fluidity. The rem unit is compatible with all properties that take a length value and has good support in modern browsers, except Internet Explorer version 8, which does not support it.

In the following segment, we’ll explore the effective utilization of the rem unit to achieve the benefits mentioned above. On that note, explore Purecode AI for designing outstanding UI components with seamless precision, all while leveraging the advantages of rem units. Discover our libraries’ components tailored to rem unit usage now!

Understanding How Rem Works

We’ve already established that rem is a document-wide CSS variable that is dependent on the font size of the root HTML element. Therefore, understanding how rem operates involves grasping its relationship to the root font size. Explicitly setting the font-size property of the root element ensures the browser acknowledges that value as equivalent to 1rem throughout your entire CSS code. Usually, the root element’s font size has a percentage value of 100% or an absolute value of 16 pixels. After declaring the root font size, rem can scale the lengths and sizes of other elements throughout the document.

For instance, if the root element’s font size is 16 pixels, then 1rem unit equals 16 pixels. Therefore, if an HTML element has a length value of 2rem, the browser will interpret it as 32 pixel values. The same phenomenon happens for 0.75rem, as the browser will also interpret it as 12-pixel values.

Frequently, developers deal with design component length values specified in absolute units. Transforming these fixed values into rem units based on the browser’s default font size can be tedious. Hence, the rem unit allows web developers to change from the browser’s default to a value that ensures easy pixel-to-rem conversion. Consider the following example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>How rem works</title>
  </head>
  <body>
    <h1>Overriding the browser's default</h1>
  </body>
</html>

CSS

html {
  font-size: 62.5%; // 16px * 0.625 = 10px;
}

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

h1 {
  text-decoration: underline;
  font-size: 4rem;
}

Why Choose Rem?

Previously, we already discussed rem as a reference to the root font size. However, have you ever wondered why developers prefer rem units to other CSS units? Let’s explore the reasons in the upcoming section.

Absolute and Relative Unit in CSS

There are two length units in CSS;

  • Absolute lengths units

  • Relative length units

Absolute length units are fixed units. They are not relative or dependent on anything and will remain the same size irrespective of other factors like parent elements or screen dimension. Examples of absolute units include the following:

  • Pixels (px)

  • Points (pt)

  • Inches (in)

  • Centimeters (cm)

  • Millimeters (mm) etc.

Relative lengths, however, depend on the length or size value of other factors like the parent element font or the viewport. This statement suggests that a change in the parent element’s length value or viewport size directly affects the element’s relative length.

Since absolute length units remain the same, they are effective when you need to know the exact dimension output, as applies to print layouts. Fixed length units are ineffective when scaling an element’s length relative to the parent element or viewport width. Therefore, relative length units excel as scalable units, offering flexibility for building responsive web pages.

However, this is insufficient rationale for opting for rem over other units. The subsequent section will delve deeper into this topic by discussing other relative units.

Understanding other relative units

Aside from rem, CSS offers other relative size units crucial to responsive web design. These units include the following:

  • em units

  • percentage units

  • viewport units

Vh and Vw

The vh unit, also known as the viewport height, equals 1% of the viewport’s vertical dimension. By specifying this unit, the browser can set the element’s vertical dimension relative to the viewport’s height. Therefore, 50vh equals half the height of the viewport. The vw unit, on the other hand, is the viewport width, which is equal to 1% of the viewport’s width. The vw unit is similar to the CSS percentage. However, since it is relative to the viewport, its value will remain constant irrespective of the parent element’s width. Consider the following code examples when using vw and vh:

Using vh

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

Using vw

.container {
  width: 50vw; /* Container width is 50% of the viewport width */
}

Percentage units

The percentage unitdenoted by %, signifies the element’s size relative to the parent’s dimension. The percentage unit creates responsive layouts that dynamically resize relative to the containing element. The following example code shows how to use percentage units in CSS:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Using percentage units</title>
  </head>
  <body>
    <div class="container">
      <img
        src="https://images.unsplash.com/photo-1705179910388-0dfc2c21a3f9?q=80&w=1887&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
      />
    </div>
  </body>
</html>

CSS:

.container {
  width: 80%;
  height: 400px;
  margin: 0 auto;
}

.container img {
  width: 100%;
  height: 100%;
}

Em

The em unit is a CSS unit that allows setting an element’s length value relative to the font size of the parent elements. For example, if a div element has a font size of 16 pixels, 1em equals 16 pixels for its descendant elements.

The em and rem units are similar since they both scale an element length value relative to its parent. However, the em unit presents a nuance for deeply nested elements. For instance, if a parent element has a font size of 1.2em, setting the font size of its direct child and nested child to 1.2em means that the nested descendant will have a font size of 1.2em x 1.2em x 1.2em. Consider the following example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>How em works</title>
  </head>
  <body>
    <div class="parent-container">
      <p>
        Direct child
        <span>Nested child</span>
      </p>
    </div>
  </body>
</html>

CSS

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.parent-container {
  text-decoration: underline;
  font-size: 1.2em;
}

.parent-container p {
  font-size: 1.2em;
}

.parent-container p > span {
  display: block;
  font-size: 1.2em; /* equals 27.648px */
  margin-top: 1rem;
}
A graphical representation of how em unit works

Therefore, avoiding explicitly defining the font size on parent elements other than the root element is recommended.

Contrasting Rem with the other relative units

Discussing each relative unit didn’t single out rem as the preferred choice for responsive design. Hence, this section will explore the distinctions between rem and other relative units to highlight the unique characteristics of rem. The table below sheds more light on their specific attributes:

Rem unitEm unitPercentage unitViewport units
Rem is relative to the root font size.Em is relative to the nearest parent font sizeThe percentage is relative to the parent element’s lengthThese units are relative to the viewport.
Rem unit offers a consistent reference point, making it easier to maintain a uniform layout.The em unit is affected by parent and ancestor font size, hence, it is inconsistent.The percentage unit provides a degree of consistency; beyond that, it scales according to the size of the element or container.Viewport units provide a consistent reference and maintain their size regardless of the parent element’s dimensions leading to overflow.
Modern browsers widely support it.It has universal support.It has wide support across most browsers.Modern browsers broadly support it.

By using rem, users can control the scaling of a web app, providing the desired accessibility and enhancing the user experience. This scalable nature of rem ensures design fluidity, a crucial aspect in today’s cross-device experience. To learn more about using rem, check the tutorial video below:

Applying Rem: Use Cases and Best Practices

Navigating the effective utilization of rem involves understanding diverse use cases and implementing best practices. In this context, we delve into the practical applications and optimal strategies for employing rem in your CSS styling.

Implementing Responsive Web Design with Rem

The beauty of using rem is the ability to create flexible and responsive designs that adapt to varying viewport sizes. The rem unit provides a scalable approach that allows rem-based sizes to scale proportionally to the root element. This unit ensures consistency across the entire design and multiple devices. Let’s discuss the strategies and best practices to achieve a responsive design with rem.

Scaling the Document Element

The rem unit is useful for building scalable components. Declaring the length values of an element in rem creates an interface that automatically grows or shrinks relative to the root font size. The following code example shows how to achieve a scalable document:

 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Scaling document</title>
  </head>
  <body>
    <div>
      <p>
        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Voluptate quod
        repellat repellendus, quae aliquid ut inventore molestias consequuntur
        delectus quas?
      </p>
      <div>
        <label for="sixtyTwo"
          >62.5%<input type="radio" class="sr-only" name="scale" id="sixtyTwo"
        /></label>
        <label for="hundred"
          >100%<input type="radio" class="sr-only" name="scale" id="hundred"
        /></label>
        <label for="oneTwenty"
          >120%<input type="radio" class="sr-only" name="scale" id="oneTwenty"
        /></label>
        <label for="oneForty"
          >140%<input type="radio" class="sr-only" name="scale" id="oneForty"
        /></label>
      </div>
    </div>
  </body>
</html>

CSS

html {
  font-size: 62.5%;
}

html:has(input#sixtyTwo:checked) {
  font-size: 62.5%;
}

html:has(input#hundred:checked) {
  font-size: 100%;
}

html:has(input#oneTwenty:checked) {
  font-size: 120%;
}

html:has(input#oneForty:checked) {
  font-size: 140%;
}

body {
  padding: 2rem 1rem;
}

p {
  font-size: 1rem;
}

label {
  border: 1px solid #ccc;
  display: inline-block;
  padding: 0.75rem 1rem;
  cursor: pointer;
}

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border-width: 0;
}

https://res.cloudinary.com/da8vqkdmt/image/upload/v1705098386/scaling_document_irbnjo.gif

Consider the following best practices when building a scalable document with rem units:

  • Choose a suitable base font size for the root element to establish a uniform scale for your design. Most frequently, the base is 16 pixels, but you can always change it to a comfortable value.

  • Use rem for specifying the width, height, margin, and padding of significant structural components. This approach ensures that they consistently scale across different screen widths.

Leveraging Rem in Media Query Breakpoints

While using rem to resize element lengths relative to the root element provides flexibility and consistency, it may fall short in ensuring layouts seamlessly adapt to varying viewport widths. Consequently, incorporating rem within media queries becomes imperative.

Media query allows web developers to dynamically adjust length values based on factors like screen width or device characteristics. Utilizing rem in media queries ensures the size and layout of elements resize based on different screen widths or device characteristics. In media queries, the calculation of rem units relies on the browser’s default size or the user-set size in browser settings, implying that font size values declared earlier in the stylesheet do not influence the length values. Therefore, altering the default font size in the stylesheet does not impact the media query block, where 1rem remains equal to 16px or the user-defined value. Consider the following code example:

html {
  font-size: 12px;
}

p {
  font-size: 1rem; /* 1rem equals 12px */
  line-height: 1.5;
}

/* Media query for smaller screens */
@media screen and (max-width: 600px) {
  html {
    font-size: 14px;
  }

  p {
    font-size: 0.9rem; /* 0.9rem equals 12.6px */
  }
}

@media screen and (min-width: 1200px) {
  html {
    font-size: 16px;
  }

  p {
    font-size: 1.2rem; /* 1.2rem equals 19.2px */
  }
}

To ensure a smooth and effective implementation when using rem in a media query, consider the following best practices:

  • Adjust Root Font Size: If necessary, adjust the root font size within specific media queries to control the overall scale of rem units for the specified viewport widths.

  • Consider Fluid Typography: Implement fluid typography techniques in media queries using rem units for font sizes. This approach allows text to scale proportionally with the viewport size.

  • Avoid Nested Media Queries: Avoid the nesting of media queries to maintain readability and simplify the styling logic.

Addressing Accessibility with Rem

Previously, we established the scalable ability of rem units to create accessible content. These accessibility considerations ensure the website or applications remain usable and readable for users with diverse needs, especially those with visual impairments. Google developers recommend using relative size units for text sizing. Designers and developers can ensure consistent scaling and legible text regardless of the user’s device or screen size by specifying length units with rem. Here are some best practices to consider when addressing accessibility with rem.

  • Set a legible base font size: Establish an easily readable base font size. Users should be able to adjust the font size of content based on their preferences without compromising readability.

    html {
      font-size: 16px; /* Set a base font size for the root element */
    }
  • Use rem for font sizes: Utilize rem units for length values to ensure scalability. This method allows users to adjust the base font size, and the entire layout will adapt proportionally.

    body {
      font-size: 1rem; /* 1rem is equal to the root font size */
    }

Tailoring Rem for Effective Use in Different Contexts

We can harness the power of rem to create visually appealing content beyond responsiveness and accessibility. Here are a few guidelines to consider in different scenarios:

  • Modular and component-based design: When building reusable components, using rem to define their size helps maintain consistency and flexibility.

  • Animations and transitions: When animating or transitioning elements, leverage rem units to ensure visual harmony, especially when combined with media queries for different screen sizes:

    html {
      font-size: 62.5%;
    }
    
    /* Apply animation to an element using rem for size */
    @keyframes scaleAnimation {
      0% {
        transform: scale(1);
      }
      50% {
        transform: scale(1.5);
      }
      100% {
        transform: scale(1);
      }
    }
    
    .animated-element {
      animation: scaleAnimation 2s infinite;
      font-size: 2rem; /* equals 20px font-size */
      padding: 1rem;
      border: 2px solid #3498db;
      margin: 2rem;
    }

Browser Compatibility and Performance Considerations

When utilizing rem, it is crucial to consider browser support and compatibility based on historical context and variations. In essence, rem has good support across modern browsers, and its use in web development ensures scalable and responsive designs. However, Internet Explorer version 8 and earlier versions do not support rem units. You may need to provide a fallback using pixels or other length units to provide support for older browsers.

In terms of performance, rem units do not pose a significant impact. The primary concern with rem is mainly due to its flexibility and the ease of creating responsive designs.

Final thoughts

The ability of rem to scale an element’s length value based on the root element’s font-size property is a powerful technique that has improved the approach to flexible, scalable, and responsive design. However, developers should be mindful of the drawbacks of using rem in CSS, including:

  • limited support for IE8 and below,

  • unintended outcomes arising from modifying the root font size globally, and

  • calculation complexity especially when dealing with media queries, etc.

Despite these challenges, rem usage can enhance a web page user experience and visual appeal. Adopting the best practices of using rem ensures consistency, simplicity, and reliability. Therefore, it’s vital to carefully consider your project’s requirements and potential challenges before choosing to use rem units.

Nevertheless, visit Purecode AI to explore our library of CSS3 components tailored to rem usage if you want to speed up your project’s development.

Further Reading

If you gained a lot of value from this article, consider reading other articles from our blog to improve your CSS skills:

Ofili Chukwuemeka Timothy

Ofili Chukwuemeka Timothy