Bigger fonts on smaller screens without @media queries or javascript?

后端 未结 5 920
梦如初夏
梦如初夏 2020-12-29 09:29

Is there an alternative for @media queries to accomplish font-size inversely proportional to the screen size? (e.g.: opposite effect of 2vw, where the font gets

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 10:11

    Here is a script solution (even if you wanted, and found, a CSS only), though this one impact the performance very little and only need to run once per resize and for one element only, the body.

    It has one benefit over CSS, you can have a min/max size, and works as a progressive enhancement for users that have script enabled so in a way risk free.

    var fontMax = 40, fontMin = 14;
    
    function sizeBodyFont() {
      var fontSize = ((screen.width / window.innerWidth) * 10);
      document.body.style.fontSize = Math.min(Math.max(fontSize,fontMin),fontMax) + 'px';
    }
    
    sizeBodyFont();
    
    (function(el) {
      window.addEventListener('resize', sizeBodyFont);  
    }(document.querySelector('#test')))
    body {
      font-size: 20px;
    }
    span {
      font-size: 100%;
    }
    div {
      font-size: 150%;
    }
    Hey there
    
    Hey there

提交回复
热议问题