Fit text perfectly inside a div (height and width) without affecting the size of the div

前端 未结 9 1845
盖世英雄少女心
盖世英雄少女心 2020-12-02 17:07

I apologise in advance as I know this question has come up many times before but I just can\'t seem to find the right solution (and believe me I\'ve tried a few!)

Ba

9条回答
  •  情话喂你
    2020-12-02 17:46

    Sorry late answer but can saves time of many, I write this code which works perfectly during resize of window.

    function fitTextInDiv(){
        if($this.find('.text-wrapper').height() > $this.find('.aligned-text').height() ){
            while( $this.find('.text-wrapper').height() > $this.find('.aligned-text').height() ) {
                 $this.find('.aligned-text').css('font-size', (parseFloat($this.find('.aligned-text').css('font-size')) + 0.1) + "px" );
            }
        }
        else if($this.find('.text-wrapper').height() < $this.find('.aligned-text').height() ){
            while( $this.find('.text-wrapper').height() < $this.find('.aligned-text').height() ) {
                $this.find('.aligned-text').css('font-size', (parseFloat($this.find('.aligned-text').css('font-size')) - 0.1) + "px" );
            }
    
         }
    }
    

    Where text-wrapper is parent and aligned-text is child div. You must specify height and width of parent element. In resize you can set height and width of parent element by using jquery then call this function.

    I write this code because I tried my many plugins but they don't support resizing window.

提交回复
热议问题