search
HomeWeb Front-endCSS TutorialAtoZ CSS Quick Tip: Benefits of rem and em Values

AtoZ CSS Quick Tip: Benefits of rem and em Values

Key Points

  • Using relative units such as "em" to set text size and internal and external spacing of elements is more flexible than using pixels, especially in responsive projects. However, "em" units can cause problems with nested elements, causing them to grow or shrink exponentially at each nesting level.
  • "rem" unit is a more reliable alternative to setting font size, as it is always calculated based on the font size of the root element. This avoids the exponential growth or shrinkage that occurs when using "em" units in nested elements.
  • For browser support, especially for older versions of Internet Explorer, you can use JS polyfill or px alternatives. If using Sass, you can create a hybrid macro and function to calculate the required rem size and automatically provide a backup plan.

This article is part of our AtoZ CSS series. You can find other entries for the series here. You can view the full text and screenshots of their corresponding videos (videos about :required pseudo-classes) here.

Welcome to our AtoZ CSS series! In this series, I will explore different CSS values ​​(and properties), each starting with different letters in the alphabet. We know that sometimes screenshots are not enough, so in this article we have added some quick tips on using rem and em values. AtoZ CSS Quick Tip: Benefits of rem and em Values

R stands for rem and em

In the initial screenshot video, we learned about the :required pseudo-class, which can be used to style forms where fields must be filled.

Forms, verification, and style status are important topics, but we didn't miss much when we first discussed :required. So let's take a look at a few quick tips for using the rem unit of measurement. But first, let's look at another relative unit: em.

Pros and cons of using em

When working with responsive items, using relative units such as em to set text size and internal and external spacing of elements is more flexible than using pixels. This is because this unit allows the element's size, spacing, and text content to grow proportionally with the font size of the parent element relative to the font size of its parent element.

Use these relative units, you can build a scale system where changing the font size value of an element has a cascading effect on the child elements within it. The proportional system is a good thing, but this behavior of em does have disadvantages.

Consider the following HTML code snippet:

<ul>
  <li>lorem ipsum</li>
  <li>dolor sit
   <ol>
    <li>lorem ipsum</li>
    <li>lorem ipsum</li>
    <li>lorem ipsum</li>
    <li>lorem ipsum</li>
   </ol>
  </li>
</ul>

This nested list is not the most common thing in the world, but it is likely to appear in terms and conditions pages or other types of official documents.

If we want the list item to stand out, we can set its font size to 1.5 times the 16px benchmark size.

<ul>
  <li>lorem ipsum</li>
  <li>dolor sit
   <ol>
    <li>lorem ipsum</li>
    <li>lorem ipsum</li>
    <li>lorem ipsum</li>
    <li>lorem ipsum</li>
   </ol>
  </li>
</ul>

But this causes problems with nested lis, as they will also be 1.5 times the size of their parent elements. The nested items will be 1.5 times higher than 24px, rather than 1.5 times higher than 16px. The result is that any nested list item will grow exponentially at each nesting level. This may not be the result the designer wants!

Similar problems also occur when nested elements and em values ​​are less than 1. In this case, any nested items will be constantly decreasing at each nesting level.

So what should we do?

Use rem to set text size

To avoid the font size increasing or decreasing, we can use alternative units.

We can use pixels, but as mentioned earlier, relative units are more flexible in responsive projects. Instead, we can use rem units because this is always based on the font size of the root element, which in the case of a website or web application is usually an html element. In .svg or .xml documents, the root elements may be different, but these types of documents are outside our current scope.

If we use rem to set the font size, it does not mean that em will never be used. I tend to use em to set the padding inside the element so that the spacing is always relative to the text size.

Use Sass to help rem browser support

rem units are only supported from IE9 and later. If you need support for IE8 (or earlier), you can use JS polyfill or provide a px alternative as follows:

li {
  font-size: 1.5em; /* 24px/16px */
}

If you use Sass, you can create a hybrid macro and a function to calculate the required rem size and automatically provide alternate solutions.

li {
  font-size: 24px;
  font-size: 1.5rem;
}

That's it. Some quick tips on using rem. If you don't use them in your current project, I highly recommend you give it a try.

FAQ for REM and EM values ​​in CSS

What are the main differences between REM and EM in CSS?

The main difference between REM and EM in CSS is that they calculate the reference point of size. EM The font size relative to its nearest parent element or current element. This means that if you nest elements, each using EM to define the font size, the sizes will be compounded and can quickly become difficult to control. On the other hand, REM is relative to the root element (or html element). This means that no matter how deep the element is nested, if you define its font size using REM, it will reference the font size of the html element, giving a consistent size on your website.

When should I use REM instead of EM in CSS?

REM is usually used when you want to create consistent and predictable resizing across your website. Because REM is relative to the root element, the resizing will remain consistent no matter how deep your element is nested. This is especially useful for building responsive designs where consistency and predictability are critical. However, when you want to create a more dynamic and scalable design, you can use EM where the size of the element is relative to its parent.

How to convert pixels to REM or EM in CSS?

To convert pixels to REM or EM, you first need to know the reference font size of the document. This is usually set on the html element, usually 16px, but can be any value. Once the reference font size is known, the REM or EM value can be calculated by dividing the desired pixel value by the reference font size. For example, if your benchmark font size is 16px, and you want a font size of 24px, the calculation is 24 / 16 = 1.5rem or 1.5em.

Can REM and EM units be used interchangeably?

While both REM and EM units can be used to define sizes in CSS, they cannot be used interchangeably because of their different reference points. REM is always relative to the root element, while EM is relative to the nearest parent element or the current element. This means that the same REM or EM value may result in different sizes depending on the context it is used.

How does browser compatibility affect the use of REM and EM units?

REM and EM units are well supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. However, if you need to support older versions of Internet Explorer (IE 8 or earlier), you should be aware that these browsers do not support REM units. In this case, you may need to use a pixel backup plan or consider using an EM unit, which has wider browser support.

How do REM and EM units affect accessibility?

REM and EM units can greatly enhance the accessibility of your website by making it easier to scale and respond to user settings. Since these units are relative, they allow users to adjust the baseline font size according to their preferences without breaking the layout. This is especially beneficial for visually impaired users who may need to increase font size for greater readability.

What are the best practices for using REM and EM units?

A best practice is to use REM units to define font sizes, margins, and padding to ensure consistency across the website. You can use EM units for elements that need to be scaled with their parent elements, such as drop-down menus or tooltips. It is also a good idea to define the benchmark font size as a percentage on the html element, which allows users to adjust the benchmark font size according to their preferences.

How do REM and EM units work with media queries?

REM and EM units can be used in media queries like any other unit. However, because these units are relative, they can make your media queries more flexible and responsive. For example, if you define breakpoints using EM units, they will scale with the base font size, allowing your layout to adapt to user settings.

Can I use REM and EM units for elements other than text?

Yes, REM and EM units can be used for any size definition in CSS, not just text. This includes width, height, fill, margin, border width, and even positioning. Using REM and EM units for these properties can make your layout more flexible and responsive.

How to deal with nested elements when using EM units?

Nested elements can be a challenge when using EM units because the sizes will be compounded. One way to deal with this is to reset the font size of the nested element to 1em, which will make it equal to the font size of its parent element. Alternatively, you can use REM units for nested elements to ensure consistency in resizing.

The above is the detailed content of AtoZ CSS Quick Tip: Benefits of rem and em Values. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Weekly Platform News: Web Apps in Galaxy Store, Tappable Stories, CSS SubgridWeekly Platform News: Web Apps in Galaxy Store, Tappable Stories, CSS SubgridApr 14, 2025 am 11:20 AM

In this week's roundup: Firefox gains locksmith-like powers, Samsung's Galaxy Store starts supporting Progressive Web Apps, CSS Subgrid is shipping in Firefox

Weekly Platform News: Internet Explorer Mode, Speed Report in Search Console, Restricting Notification PromptsWeekly Platform News: Internet Explorer Mode, Speed Report in Search Console, Restricting Notification PromptsApr 14, 2025 am 11:15 AM

In this week's roundup: Internet Explorer finds its way into Edge, Google Search Console touts a new speed report, and Firefox gives Facebook's notification

The Power (and Fun) of Scope with CSS Custom PropertiesThe Power (and Fun) of Scope with CSS Custom PropertiesApr 14, 2025 am 11:11 AM

You’re probably already at least a little familiar with CSS variables. If not, here’s a two-second overview: they are really called custom properties, you set

We Are ProgrammersWe Are ProgrammersApr 14, 2025 am 11:04 AM

Building websites is programming. Writing HTML and CSS is programming. I am a programmer, and if you're here, reading CSS-Tricks, chances are you're a

How Do You Remove Unused CSS From a Site?How Do You Remove Unused CSS From a Site?Apr 14, 2025 am 10:59 AM

Here's what I'd like you to know upfront: this is a hard problem. If you've landed here because you're hoping to be pointed at a tool you can run that tells

An Introduction to the Picture-in-Picture Web APIAn Introduction to the Picture-in-Picture Web APIApr 14, 2025 am 10:57 AM

Picture-in-Picture made its first appearance on the web in the Safari browser with the release of macOS Sierra in 2016. It made it possible for a user to pop

Ways to Organize and Prepare Images for a Blur-Up Effect Using GatsbyWays to Organize and Prepare Images for a Blur-Up Effect Using GatsbyApr 14, 2025 am 10:56 AM

Gatsby does a great job processing and handling images. For example, it helps you save time with image optimization because you don’t have to manually

Oh Hey, Padding Percentage is Based on the Parent Element's WidthOh Hey, Padding Percentage is Based on the Parent Element's WidthApr 14, 2025 am 10:55 AM

I learned something about percentage-based (%) padding today that I had totally wrong in my head! I always thought that percentage padding was based on the

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)