undefinedfix
Sign in

How to calculate the value of width and height with REM? Who is the reference?

dgtsf edited in Mon, 05 Sep 2022

How to calculate the width and height of REM? For example, HTML {font}- size:62.5%; }So font- size:2rem; And font- size:20px It's the same, but width:20rem And width:200px It's different. So, when you want to use REM to set width and height, how to calculate? Who is the reference?

4 Replies
bszsk
commented on Mon, 05 Sep 2022

The problem of setting value can be seen in this https://segmentfault.com/q/1010000002411895

Why does the calculation of font size 2rem = 20px width 2rem = 24px appear

It seems that chrome limits the minimum font size to 12px

user14340730
commented on Mon, 05 Sep 2022

Mobile terminal: direct VW is recommended. Rem is too awkward to use

tanish
commented on Mon, 05 Sep 2022

Rem is based on the font size of the root element, which is HTML tag. Generally you will see the following JS

(function (doc, win) {
  var docEl = doc.documentElement,
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
    recalc = function () {
      var clientWidth = docEl.clientWidth;
      if (!clientWidth) return;
      if (clientWidth >= 750) {
        // 这里的750取决于设计稿的宽度
        docEl.style.fontSize = '100px';
      } else {
        docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
      }
    };

  if (!doc.addEventListener) return;
  win.addEventListener(resizeEvt, recalc, false);
  recalc();
  // doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
``
ioajz
commented on Tue, 06 Sep 2022

REM takes the font size of HTML (root element) as the reference. Generally speaking, you can change the font size of HTML in different screens through media query @ media screen and (min width: PX) and (max width: PX) and (orientation: portal) {font size: * PX}, so that the elements using REM can be changed, so as to achieve the effect of adaptation

lock This question has been locked and the reply function has been disabled.