How to scale text size compared to container

前端 未结 4 1538
挽巷
挽巷 2021-01-24 06:43

How would you scale text size based on container size. Other questions state it can\'t be done with css, if not how would you go about it?

4条回答
  •  醉梦人生
    2021-01-24 07:11

    Here's how I accomplished it- I wrapped the text in a span and scaled that down with a CSS transform:

    Scale this text to fit inside the parent div.

    jQuery:

    $(function(){
        var textWidth = $('#fit-text-in-here span').width(),
            fitWidth = $('#fit-text-in-here').width();
    
        if (textWidth > fitWidth) {
            var scaleTo = fitWidth / textWidth,
                offset = (fitWidth - textWidth)/2;
    
            $('#fit-text-in-here span').css({
                '-moz-transform': 'scale('+scaleTo+')',
                '-webkit-transform': 'scale('+scaleTo+')',
                '-o-transform': 'scale('+scaleTo+')',
                'transform': 'scale('+scaleTo+')',
                'margin-left': offset,
                'display': 'inline-block'
            });
        }
    });
    

提交回复
热议问题