Calculate the font size to fill the container with text

Possible duplicate:
Auto-size dynamic text to fill a fixed-size container

If the container contains only plain text without a child, then the following code is a working solution:

(function($) { $.fn.textfill = function(options) { return this.each(function() { var text = $(this).text(); $(this).text(''); var container = $('<span />').text(text).appendTo($(this)); var min = 1, max = 200, fontSize; do { fontSize = (max + min) / 2; container.css('fontSize', fontSize); var multiplier = $(this).height()/container.height(); if (multiplier == 1) { min = max = fontSize} if (multiplier > 1) { min = fontSize} if (multiplier < 1) { max = fontSize} } while ((max - min) > 1); fontSize = min; if ($(this).width() < container.width()) { min = 1; do { fontSize = (max + min) / 2; container.css('fontSize', fontSize); var multiplier = $(this).width()/container.width(); if (multiplier == 1) { min = max = fontSize} if (multiplier > 1) { min = fontSize} if (multiplier < 1) { max = fontSize} } while ((max - min) > 1); fontSize = min; } container.remove(); $(this).text(text); var minFontSize = options.minFontPixels; var maxFontSize = options.maxFontPixels; $(this).css('fontSize', minFontSize && (minFontSize > fontSize) ? minFontSize : maxFontSize && (maxFontSize < fontSize) ? maxFontSize : fontSize); }); }; })(jQuery); 

See the demo here .

But what if the container contains children, say:

 <div><span class="c1">text1</span>main text<span class="c2">text2</span></div> 

and we also want to authorize children by keeping the text as high as the "main text", which is the text node? Children may have a different font family or other parameters.

How can the algorithm be improved to get such results?

+4
source share
2 answers

I played a little, and it seems to me that I found a solution. The algorithm changes as follows:

  • first you need to find the old font size for the target element and all its children (not just the first level).
  • then you need to calculate the coefficient, i.e. the font size must be changed, the coefficient must be calculated in parallel with the new font size calculation
  • and apply this coefficient to the final font size of the target and for all its children

DEMO works here

UPDATE

here is the solution you need, the previous one does a little more than you need, I just want to save it, maybe others will find it useful. I also want to note that this second solution is very similar to the first, with the exception of the part of the coefficient that is not needed in this case.

+4
source

Have you looked into the FitText jQuery plugin?

http://fittextjs.com/

So good.

-1
source

Source: https://habr.com/ru/post/1438911/


All Articles