Font scaling based on width of container

后端 未结 30 2953
面向向阳花
面向向阳花 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:05

    Using vw, em & co. works for sure, but IMO it always needs a human's touch for fine-tuning.

    Here's a script I just wrote based on @tnt-rox' answer that tries to automatize that human's touch:

    $('#controller').click(function(){
        $('h2').each(function(){
            var
                $el = $(this),
                max = $el.get(0),
                el = null
            ;
            max =
                max
                ? max.offsetWidth
                : 320
            ;
            $el.css({
                'font-size': '1em',
                'display': 'inline',
            });
            el = $el.get(0);
    
            el.get_float = function(){
                var
                    fs = 0
                ;
                if (this.style && this.style.fontSize) {
                    fs = parseFloat(this.style.fontSize.replace(/([\d\.]+)em/g, '$1'));
                }
                return fs;
            };
    
            el.bigger = function(){
                this.style.fontSize = (this.get_float() + 0.1) + 'em';
            };
    
            while (el.offsetWidth < max) {
                el.bigger();
            }
    
            // Finishing touch.
            $el.css({
                'font-size': ((el.get_float() -0.1) +'em'),
                'line-height': 'normal',
                'display': '',
            });
        });  // end of (each)
    });    // end of (font scaling test)
    div {
      width: 50%;
      background-color: tomato;
      font-family: 'Arial';
    }
    
    h2 {
      white-space: nowrap;
    }
    
    h2:nth-child(2) {
      font-style: italic;
    }
    
    
    

    Lorem ipsum dolor

    Test String

    Sweet Concatenation

    Font Scaling

    It basically reduces the font-size to 1em and then starts incrementing by 0.1 until it reaches maximum width.

    JSFiddle

提交回复
热议问题