Home >Web Front-end >CSS Tutorial >Rem in CSS: Understanding and Using rem Units

Rem in CSS: Understanding and Using rem Units

Christopher Nolan
Christopher NolanOriginal
2025-02-10 13:53:10740browse

Rem in CSS: Understanding and Using rem Units

In-depth understanding of rem units in CSS: a relatively large unit with excellent browser compatibility and learn how to use them effectively.

Key Points

  1. Understand rem units: Learn CSS rem units, which relative to the font size of the root element, provides a consistent method for font size and spacing in your UI.
  2. Compare rem and em units: Explore the difference between rem and em units in CSS. rem provides a simpler and more consistent method of size adjustment, avoiding the complexity related to em unit nesting sex.
  3. Practical application and accessibility: Discover the practical use of rem units in responsive design, scaling documents and ensuring network accessibility, allowing users to adjust the font size according to their preferences.

What is a rem unit?

In CSS, rem stands for "root em", which is a unit of measurement that represents the font size of the root element. This means that 1rem is equal to the font size of the html element, and for most browsers the default is 16px. Using rem can help ensure consistency in font size and spacing throughout the UI.

According to the W3C specification, the definition of a rem unit is:

is equal to the calculated value of font-size on the root element. When specified on the font-size property of the root element, the rem unit refers to the initial value of the property.

rem units and em units

The difference between rem units and em units is that the font size of the em units relative to its own element, not the root element. Therefore, they may be cascading and lead to unexpected results. Let's consider the following example, we want the list to have a font size of 12px, in case the root font size is the default 16px:

<code>html {font-size: 100%;}
ul {font-size: 0.75em;}</code>

If we have a list nested in another list, the font size of the internal list will be 75% of its parent size (9px in this case). We can still overcome this problem by using something like:

<code>ul ul {font-size: 1em;}</code>

This does work, but we still have to pay great attention to the deeper nesting situation.

With rem unit, things are much simpler:

<code>html {font-size: 100%;}
ul {font-size: 0.75rem;}</code>

Since all sizes refer to the root font size, it is no longer necessary to handle nesting cases in separate declarations.

Use rem units for font size resizing

One of the pioneers of font size resizing using rem units was Jonathan Snook, who published an article on font size resizing using REM in May 2011. Like many other CSS developers, he has to face the problems brought by em units in complex layouts.

At that time, older versions of IE still had a large market share, and they could not scale text using pixel size. However, as we saw earlier, it is easy to ignore nesting and get unexpected results using em units.

The main problem with using rem for font size resizing is that these values ​​are not very convenient to use. Let's look at an example of some common font sizes expressed in rem units, of course, assuming the base size is 16px:

  • 10px = 0.625rem
  • 12px = 0.75rem
  • 14px = 0.875rem
  • 16px = 1rem (benchmark)
  • 18px = 1.125rem
  • 20px = 1.25rem
  • 24px = 1.5rem
  • 30px = 1.875rem
  • 32px = 2rem

As we can see, these values ​​are not convenient for doing calculations. So Snook uses a technique called "62.5%. This is by no means a new discovery, as it has been used in em units:

<code>html {font-size: 100%;}
ul {font-size: 0.75em;}</code>

Snook's solution becomes:

Since the rem unit is relative to the root element, Snook's solution becomes:
<code>ul ul {font-size: 1em;}</code>

We must also consider other browsers that do not support rem. So the above code is actually written like this:
<code>html {font-size: 100%;}
ul {font-size: 0.75rem;}</code>

While this solution seems to be close to the status of the "Golden Rule", some people recommend not to use it blindly. Harry Roberts wrote his own opinion on the use of rem units. In his opinion, while the 62.5% solution makes the calculation easier (because the font size in px is 10 times its rem value), it ultimately forces developers to explicitly rewrite all font sizes in their website.

The third view comes from Chris Coyier of CSS-Tricks. His solution uses all three units we currently encounter. He retains the root size defined in px, modules defined in rem units, and elements within modules in em units. This approach makes it easier to manipulate global size, which scales the types in the module, while the module contents are scaled based on the font size of the module itself. Louis Lazaris later discussed this concept in "The Power of Em Units in CSS".

In the following example, you can see what Chris's method looks like:

[CodePen sample link - CodePen's embedded code should be inserted here, but since I can't access the external website, I can't provide it. ]

In practice, major frameworks like Bootstrap 4 and Material Design Guide use rem units to resize text content.

The one that needs to be mentioned in particular is Material-UI, which is a very popular collection of React components. Not only do they resize text in the same way, they also provide a mechanism to achieve the “10px simplification” we mentioned earlier.

Another recent project, Every Layout, combines em and rem units in a very creative way. It is closest to the aforementioned model overview of Chris Coyier and it uses em units to emphasize inline elements such as SVG icons, spans, or other similar elements.

As you can see, there is no "all-purpose" solution. Possible combinations are limited only by the developer's imagination.

Use rems

in media query breakpoints

The use of em or rem units in media queries is closely related to the concept of "best president" and its impact on reading experience. Smashing Magazine published a comprehensive research article on web typesetting, titled "Size is Important: Balanced Line Length and Font Size in Responsive Web Design." Among many other interesting things, the article gives an estimate of the best row length: between 45 and 75-85 characters (including spaces and punctuation), where 65 is the "ideal" target value.

Using a rough estimation of 1rem = 1 character, we can control the text flow of single column content, using a mobile-first approach:

<code>html {font-size: 100%;}
ul {font-size: 0.75em;}</code>

However, when used as units in media queries, rem and em units have an interesting detail: they always keep the same value of 1rem = 1em = the font size set by the browser. The reason for this behavior is explained in the media query specification (highlighted):

The relative units in media queries are based on the initial value, which means that units are never based on the declared result. For example, in HTML, the em unit relative to the initial value of the font-size is defined by the user agent or user's preferences, rather than any style on the page.

Let's take a quick look at an example of this behavior:

[CodePen sample link - CodePen's embedded code should be inserted here, but since I can't access the external website, I can't provide it. ]

First, in our HTML we have an element where we will write the width of the viewport:

<code>ul ul {font-size: 1em;}</code>

Next, we have two media queries, one using rem units and the other using em units (this uses Sass for simplicity):

<code>html {font-size: 100%;}
ul {font-size: 0.75rem;}</code>

Finally, we use some jQuery to display the viewport width on the page and update the value when the window size changes:

<code>body { font-size:62.5%; } /* =10px */h1 { font-size: 2.4em; } /* =24px */p { font-size: 1.4em; } /* =14px */li { font-size: 1.4em; } /* =14px? */</code>

We start with the 62.5% trick to show that the modified root font size has no effect on the values ​​used in the media query. When we change the width of the browser window, we can see that the first media query starts at 320px (20 × 16px) and the second media query starts at 480px (30 × 16px). The font size change we declared has no effect on breakpoints. The only way to change the media query breakpoint value is to modify the default font size in the browser settings.

Therefore, there is actually no difference between using em or rem units in media query breakpoints. Zurb Foundation (currently v6.5.3 at the time of writing) uses em units in media queries.

Accessibility Pursuit

We have seen above that the ability to scale based on the root font size makes rem units very useful for accessibility. Google developers recommend using relative units for text resizing.

The staff behind the internet archives conducted an empirical study and the results showed that a large number of users change the default font size in their browser settings. By using rem and other relative units, you can respect users’ decisions about how they want to browse the web.

Scaling documents using rem units

The third use we can find for rem units is to build scalable components. By representing width, margins, and padding in rem units, you can create interfaces that grow or shrink synchronously with the root font size. Let's see how this thing works using several examples.

[CodePen Example Link 1 - CodePen's embedded code should be inserted here, but since I can't access the external website, I can't provide it. ]

[CodePen Example Link 2 - CodePen's embedded code should be inserted here, but since I can't access the external website, I can't provide it. ]

Conclusion

We end our encounter with the CSS rem unit here. It is obvious that there are many advantages to using these units in our code, such as responsiveness, scalability, improved reading experience and greater component definition flexibility. Rem units are not a universal universal solution, but with careful deployment, they can solve many of the problems that have plagued developers for years. It depends on each of us to unlock the full potential of rems. Launch your editor, conduct experiments, and share your results with the rest of us.

For more information on CSS size units, see:

  • Understanding the units of length in CSS
  • New CSS3 relative font size units
  • The power of em units in CSS

Of course, Rem is not the only available CSS unit. Check out our CSS Size Unit Overview.

FAQs about Rem in CSS

What is the difference between rem and em units in CSS?

The main difference between rem and em units in CSS is that they calculate the reference point of size. The font size of the em unit relative to its nearest parent element. If you nest elements, each level may have different font sizes depending on the size of its parent, resulting in a compound size. On the other hand, rem stands for "root em". It is only relative to the root element (html), which makes it consistent in use anywhere in the document. This makes rem units easier to predict and manage in large CSS files.

How to convert pixels to rem units in CSS?

To convert pixels to rem units, you need to know the base font size of the document, usually 16px (the default size for most browsers). The conversion formula is: target pixel value/reference font size = rem value. For example, if you want a font size of 24px, the equivalent value in rem is 24px/16px=1.5rem.

Can I use rem units for properties other than font size?

Yes, rem units can be used for any CSS attribute that requires a length value, not just the font size. This includes properties such as width, height, padding, margin and line-height. Using rem units for these properties can help maintain proportional spacing and layout over different screen sizes.

Does all browsers support rem units?

Yes, all modern browsers support rem units widely, including Chrome, Firefox, Safari, Edge, and Internet Explorer 9 and later. However, for older browsers that do not support rem units, you can provide pixel fallback.

How can using rem units be beneficial to responsive design?

rem units are very beneficial for responsive design. Since rem is relative to the root element, changing the root font size allows you to resize all elements defined in rem. This can be done in media queries, allowing different font sizes to be provided for different screen sizes, making your design responsive.

What is the impact of using rem units on accessibility?

Using rem units can significantly improve accessibility of your website. Some users may adjust the default font size of their browsers for greater readability. Because the rem unit is relative to this benchmark font size, it allows your website’s layout and spacing to adjust according to user preferences, improving the overall user experience.

How to override styles defined in rem units?

You can override styles defined in rem units by using CSS specificity or !important rules. However, it is recommended to use these methods with caution and instead build your CSS in a way that minimizes the need for coverage.

Can I use rem units in combination with other units such as pixels or percentages?

Yes, rem units can be used in combination with other units such as pixels or percentages. This can provide greater flexibility for your design. For example, you can use pixels for border width (no need to scale with text size) and rem units for fill (needed).

How to set the base font size of rem units?

The base font size of the rem unit is set using the font-size property on the root element (html). For example, if you want the benchmark font size to be 10px, you can use: html { font-size: 10px; }. All rem units will then be relative to this size.

What are the best practices for using rem units in CSS?

Some best practices for using rem units in CSS include: setting a reasonable baseline font size on the root element; using rem units for properties that need to scale with text size; providing pixel fallback for older browsers; and Test your design at different font sizes to ensure it remains accessible and visually balanced.

The above is the detailed content of Rem in CSS: Understanding and Using rem Units. 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