Font scaling based on width of container

后端 未结 30 3045
面向向阳花
面向向阳花 2020-11-21 04:35

I\'m having a hard time getting my head around font scaling.

I currently have a website with a body font-size of 100%. 100% of what though? This seems t

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 05:22

    In order to make font-size fit its container, rather than the window, see the resizeFont() function I have shared in this question (a combination of other answers, most of which are already linked here). It is triggered using window.addEventListener('resize', resizeFont);.

    Vanilla JavaScript: Resize font-awesome to fit container

    JavaScript:

    function resizeFont() {
      var elements  = document.getElementsByClassName('resize');
      console.log(elements);
      if (elements.length < 0) {
        return;
      }
      _len = elements.length;
      for (_i = 0; _i < _len; _i++) {
        var el = elements[_i];
        el.style.fontSize = "100%";
        for (var size = 100; el.scrollHeight > el.clientHeight; size -= 10) {
          el.style.fontSize = size + '%';
        }
      }
    }
    

    You could perhaps use vw/vh as a fallback, so you dynamically assign em or rem units using JavaScript, ensuring that the fonts do scale to the window if JavaScript is disabled.

    Apply the .resize class to all elements containing text you wish to be scaled.

    Trigger the function prior to adding the window resize event listener. Then, any text which doesn't fit its container will be scaled down when the page loads, as well as when it is resized.

    NOTE: The default font-size must be set to either em,rem or % to achieve proper results.

提交回复
热议问题