Font scaling based on width of container

后端 未结 30 2952
面向向阳花
面向向阳花 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条回答
  •  清酒与你
    2020-11-21 05:13

    My problem was similar, but related to scaling text within a heading. I tried Fit Font, but I needed to toggle the compressor to get any results, since it was solving a slightly different problem, as was Text Flow.

    So I wrote my own little plugin that reduced the font size to fit the container, assuming you have overflow: hidden and white-space: nowrap so that even if reducing the font to the minimum doesn't allow showing the full heading, it just cuts off what it can show.

    (function($) {
    
      // Reduces the size of text in the element to fit the parent.
      $.fn.reduceTextSize = function(options) {
        options = $.extend({
          minFontSize: 10
        }, options);
    
        function checkWidth(em) {
          var $em = $(em);
          var oldPosition = $em.css('position');
          $em.css('position', 'absolute');
          var width = $em.width();
          $em.css('position', oldPosition);
          return width;
        }
    
        return this.each(function(){
          var $this = $(this);
          var $parent = $this.parent();
          var prevFontSize;
          while (checkWidth($this) > $parent.width()) {
            var currentFontSize = parseInt($this.css('font-size').replace('px', ''));
            // Stop looping if min font size reached, or font size did not change last iteration.
            if (isNaN(currentFontSize) || currentFontSize <= options.minFontSize ||
                prevFontSize && prevFontSize == currentFontSize) {
              break;
            }
            prevFontSize = currentFontSize;
            $this.css('font-size', (currentFontSize - 1) + 'px');
          }
        });
      };
    })(jQuery);
    

提交回复
热议问题