Rem, as a low-key unit of length, has been reused in screen adaptation due to the rise of mobile web. Rem front-end developers can easily achieve the effect of design requirements in various screen sizes through proportional scaling.

Rem’s official definition is “The font size of The root element.”, which takes The font size of The root node as The reference value for length calculation. It is generally believed that the root node of a web page is the HTML element, so the method used is to set the FONT size of the HTML element for screen adaptation, but is it really that simple?

First let’s take a look at the common schemes for using REM to achieve screen adaptation on mobile phones.

Make the design 640px wide (designWidth = 640) and set the screen width at 640px to 1rem=100px (rem2px =100).

The advantages of setting 1rem=100px are self-evident. The front-end developer can convert the PX value measured in the UI map into the corresponding REM value by directly shifting the decimal point when cutting the map and reconstructing the page, which is convenient and fast.

In addition, in head we also set: viewport is important, but not the focus of this article, so we will not expand, interested students can search on their own.

Let’s take a look at the specific plan:

The following four schemes, shared by colleagues, all use proportional scaling — get the ratio of the width of the target screen to the width of the design, use it as the base value for REM (the scaling factor), and set it to the font size of the HTML tag. The only difference is in performance trade-offs and writing habits.

Plan 1

@media screen and (min-width: 320px) {html{font-size:50px; }} @media screen and (min-width: 360px) {HTML {font-size:56.25px; }} @media screen and (min-width: 375px) {HTML {font-size: 58.5937px; }} @media screen and (min-width: 400px) {HTML {font-size:62.5px; }} @media screen and (min-width: 414px) {HTML {font-size:64.6875px; }} @media screen and (min-width: 440px) {HTML {font-size:68.75px; }} @media screen and (min-width: 480px) {html{font-size:75px; }} @media screen and (min-width: 520px) {HTML {font-size:81.25px; }} @media screen and (min-width: 560px) {HTML {font-size:87.5px; }} @media screen and (min-width: 600px) {HTML {font-size:93.75px; }} @media screen and (min-width: 640px) {html{font-size:100px; }} @media screen and (min-width: 680px) {HTML {font-size:106.25px; }} @media screen and (min-width: 720px) {HTML {font-size:112.5px; }} @media screen and (min-width: 760px) {HTML {font-size:118.75px; }} @media screen and (min-width: 800px) {html{font-size:125px; }} @media screen and (min-width: 960px) {html{font-size:150px; }}Copy the code

Plan 3

var designWidth = 640, rem2px = 100;
document.documentElement.style.fontSize = 
  ((window.innerWidth / designWidth) * rem2px) + 'px';Copy the code