Understanding and using REM units in CSS

Source: Internet
Author: User
What is REM

Maybe you've heard "R.E.M" before you use the radio or other music players. The word. In the eye of the band, the word is the abbreviation for "The rapid movement of the eyeball during light sleep", whereas in CSS, REM represents "an EM unit based on the root element". He won't let you abandon your religious beliefs nor will you believe the man who is far away from the moon, but it can help you achieve a harmonious and smooth design.

According to the definition of 1rem in the code:

1rem is the computed value equal to the font-size of the root element. When the font-size of a root element is explicitly specified, REM units are referenced by the initial value of the attribute.

This means that 1rem is equal to the font size of the HTML element (most browser root elements have a font size of 16px)

Rem Units vs Em units

The main problem with EM units is that they are associated with user elements. In this case, these elements can be nested with each other and cause unexpected results. Let's consider the following example, where the text size of the root element is the default value of 16px, we want all lists to have a font size of 12px:

HTML {   font-size:100%;}  UL {   font-size:0.75em;}

If a list is nested under another list, the font size of the inner list will be 75% (that is, 9px) of the outer list font size, and we can still solve the problem with a few lines of code:

UL ul {   font-size:1em;}

This will solve the problem, but I still need to pay special attention to those elements that are particularly deep in the nest.

When you use REM units, things become simple:

HTML {   font-size:100%;}  UL {   Font-size:0.75rem;}

When all dimensions are referenced with the text size of the root element, it is no longer necessary to define the styles separately for the nested elements.

Define text size using REM units

Jonathan Snook was the first developer to use REM units to define text size, and as early as May 2011, he published an article titled "Using REM to define text size." Like most CSS developers, he has to solve a series of problems with the EM unit in a complex layout.

At the time, older versions of IE still had a large market share, and they could not scale the text defined by PX. However, as we have seen before, in the case of EM units, it is easy to forget the nesting relationship before the element and get an unexpected result.

The problem with using REM units to define the maximum size of text is that these values are a bit difficult to use. Let's take a look at an example, assuming that the text size of the root element is 16px, our usual text size is converted to REM values as follows:

10px = 0.625rem

12px = 0.75rem

14px = 0.875rem

16px = 1rem (Base)

18px = 1.125rem

20px = 1.25rem

24px = 1.5rem

30px = 1.875rem

32px = 2rem

As we have seen, these values are very inconvenient to calculate. Therefore, Snook uses a method called 62.5 to solve this problem. This is not an innovation, however, as it has already been used in EM units:

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

Because REM units are associated with root elements, the Snook improved scheme becomes:

HTML {font-size:62.5%;}/* =10px * * body {font-size:1.4rem;}/* =14px */h1 {Font-size:2.4rem;}/* =24px *

One thing worth considering is that some browsers do not support REM units. So the code above can be rewritten in the following way

HTML {     font-size:62.5%;}  body {     font-size:14px;     Font-size:1.4rem; }  h1 {     font-size:24px;     Font-size:2.4rem; }

Although this solution seems to be the best solution, it is not recommended to use this approach. Harry Roberts wrote an article that recorded some of his feelings in the process of actually using REM units. From his point of view, although 62.5% of this solution makes computing simple (because the font size is exactly 10 times times the value of rem in pixels), he forces developers to rewrite all the text sizes in their sites.

Chris Coyier presented a third solution in Css-tricks. His solution takes full advantage of the three units we have encountered so far. The length unit of the root element is still px, the module uses REM units, and the elements within the module use EM units. This way it is easy to manipulate the size of the root element, the scaling module, and the size of the content within the module to scale with the size of the module's own text. Louis Lazaris then raised his point in the power of the EM unit in CSS.

In the example below you can see how Chris's solution works:

The code can look at SitePoint (@SitePoint click Preview) in Codepen, "How to use EM and REM units in CSS" and click Preview.

As you can see, there is no use of new technology to solve this problem. Some combinations may only be limited by the imagination of the developer.

Using REM units in media queries

The use of EM and REM units in media queries is closely related to the concept of "best line Length" and provides a smooth reading experience for users. In September 2014, smashing Magazine published an article in the Web typography titled Size: Mastering the balance between text size and line width in web responsive design. Most interestingly, the article gives the best width of the line, 45 to 85 characters (including spaces and punctuation), and 65 is the ideal line width value.

A rough estimate of the size of a byte is 1rem, and with this method we can control the single-line text flow of the content in a mobile-first way:

. container {   width:100%;}  @media (Min-width:85rem) {   . container {     width:65rem;   }}

However, there is an interesting detail when using EM and REM units as a condition for media queries in media queries: 1 rem,1em and the browser default text size these three values represent the same value. The reasons for this can be explained in the Media Query specification (especially):

The relative units in the poll are based on an initial value, which means that these units are never built on the result of the claim. For example, in HTML, EM units are related to the initial text size set in the user's browser or user preferences, rather than the text size defined in the styles on the page.

Let's take a look at a small example of this feature:

See a demo of media queries on Codepen

First, in our HTML document, there is an element that will show the width of the viewport:

' Document width: <span></span>px '

Next is two media query statements, one using REM units and the other using EM units (here for simplicity, using Sass)

HTML {   font-size:62.5%;/* 62.5% of 16px = 10px *    /@media (Min-width:20rem) {/     * 20*16px = 320px */     back Ground-color:lemonchiffon;     font-size:200%;     /* 200% of 16px = 32px   *    /} @media (Min-width:30em) {/     * 30*16px = 480px */     background-color:lightblue;< c10/>font-size:300%; /* 300% of 16px = 48px */(translated: Original is 48px)   }}

Finally, we use a little jQuery to display the width of the viewport on the page and update the value when the window is scaled:

$ (' span '). Text ($ (window). width ());  $ (window). On (' Resize ', function (e) {   $ (' span '). Text ($ (window). width ());});

At the beginning, we used the 62.5% method to illustrate that changing the font size of the root element does not have any effect on media queries. When we change the width of the window, we can see that the first media query starts to work at the time of the 480px, and the second media query starts to work. Any change to the text size declaration in the media query does not work. The only thing that can change the width of a media query is to change the default text size in the browser.

For this reason, it is less important to use EM units or REM units in media query statements. In fact, both Foundation V5 and recently released Bootstrap V4 Alpha have used EM units in their media queries.

Use REM units to scale documents

The third Way we can find the use of REM units is to build a scalable component. Using REM to define the width of an element, the margins and padding are made possible by using the font size of the root element as an interface to scale the elements. We can see how this works by the following two examples.

Use REM to scale the document instance one

In this example, we change the text size of the root element through the media query. As mentioned in the previous section, the goal is to customize the different reading experiences for the user under different devices. The width, margin, and padding are expressed in rem units, so that all elements are scaled based on the user's device size.

Let's look at another example:

Code can see SitePoint (@SitePoint click Preview) in Codepen write "Use REM dynamic Zoom module" Click to preview

In the second example, we use JavaScript to do the same thing. This time the user manually controls the size of the interface according to their needs. We can store user data in a variety of ways (using databases, cookies, and local storage) so that users can be given a personalized system based on user preferences.

Summarize

Here's a summary of what we've learned so far about REM units in CSS. Obviously, using REM in a project has many advantages, such as: responsive, scalable, increased reading experience, and increased flexibility for custom elements. Although REM is not a universal solution, it can solve problems that have plagued developers for years by using caution. Each of us can tap into all the potential of REM. Start with your editor, experiment and share your results with us.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.