Responsive font size using CSS/jQuery

前端 未结 3 623
天涯浪人
天涯浪人 2021-01-17 01:57

I want to create a responsive text inside a div.

I tried jquery-textfill and FlowType, but they are not working for me at all.

FlowType does

3条回答
  •  温柔的废话
    2021-01-17 02:47

    For anyone who stumbles upon this old post, I have found a solution I consider perfect.

    You take this beautiful plugin written by Dave Rupert, configure the settings to your liking, and I added a wrapper for it that allows you to define the elements you want to resize. It also stores the original font size so when you scale back up, the text is limited by it's original size, otherwise it scales without limit.

    Here's a snippet and a jsfiddle. JSFiddle

    NOTE: the snippet only runs on resize in JSFiddle so be sure to resize your screen. In production it runs on load.

    var headings = [$('h1'), $('h2'), $('h3')]
    
      $.each(headings, function(index, heading) {
    
        var fontsize = heading.css('font-size');
        $(window).on('load resize', function() {
          if (heading.parent()[0] &&
            heading.parent()[0].scrollWidth > $('.container').innerWidth()) {
            heading.fitText(1, {
              minFontSize: '10px',
              maxFontSize: fontsize
            });
          }
        });
      });
    
    
      /*global jQuery */
      /*!
       * FitText.js 1.2
       *
       * Copyright 2011, Dave Rupert http://daverupert.com
       * Released under the WTFPL license
       * http://sam.zoy.org/wtfpl/
       *
       * Date: Thu May 05 14:23:00 2011 -0600
       */
    
      $.fn.fitText = function(kompressor, options) {
        // Setup options
        var compressor = kompressor || 1,
          settings = $.extend({
            'minFontSize': Number.NEGATIVE_INFINITY,
            'maxFontSize': Number.POSITIVE_INFINITY
          }, options);
        return this.each(function() {
          // Store the object
          var $this = $(this);
          // Resizer() resizes items based on the object width divided by the compressor * 10
          var resizer = function() {
            $this.css('font-size', Math.max(Math.min($this.width() / (compressor * 10), parseFloat(settings.maxFontSize)), parseFloat(settings.minFontSize)));
          };
          // Call once to set.
          resizer();
          // Call on resize. Opera debounces their resize by default.
          $(window).on('resize.fittext orientationchange.fittext', resizer);
        });
      };
    
    .container {
      width: 80vw;
      background: yellow;
    }
    
    h1 {
      font-size: 5rem;
    }
    
    h2 {
      font-size: 4rem;
    }
    
    h3 {
      font-size: 3rem;
    }
    
    h4 {
      font-size: 1rem;
    }
    
    
    

    GIGANTICFONT

    LargishFont

    Mediumfont

    smallfont

提交回复
热议问题