Justin808
Justin808

Reputation: 21512

How can I autoscale the font size to fit the contents of a div?

I have a div with some text:

<div style="white-space:nowrap;overflow:none;width:50px;">
  With some text in it
</div>

How can I scale the font size of the text so all of the text is visible?

Upvotes: 11

Views: 15363

Answers (5)

Afflatus
Afflatus

Reputation: 2452

Also came across this Jquery script when I was looking for the same thing. It has the added benefit over the others, as far as I quickly tell, is that it also adjusts for height as well as width.

Comes from here: http://www.metaltoad.com/blog/resizing-text-fit-container

 function adjustHeights(elem) {
      var fontstep = 2;
      if ($(elem).height()>$(elem).parent().height() || $(elem).width()>$(elem).parent().width()) {
        $(elem).css('font-size',(($(elem).css('font-size').substr(0,2)-fontstep)) + 'px').css('line-height',(($(elem).css('font-size').substr(0,2))) + 'px');
        adjustHeights(elem);
      }
    }

Upvotes: 0

FlavorScape
FlavorScape

Reputation: 14289

I've been doing something like this, to set the text scale relative to the parent (or window) width / height. You can avoid jQuery by using offsetWidth and offsetHeight instead of width.

var setBodyScale = function () {

    var scaleSource = $(window).width(), // could be any div
        scaleFactor = 0.055,
        maxScale = 500,
        minScale = 75; //Tweak these values to taste

    var fontSize = (scaleSource * scaleFactor) - 8; //Multiply the width of the body by the scaling factor:

    if (fontSize > maxScale) fontSize = maxScale;
    if (fontSize < minScale) fontSize = minScale; //Enforce the minimum and maximums

    $('html').css('font-size', fontSize + '%'); // or em
}

Upvotes: 3

maxcobmara
maxcobmara

Reputation: 391

Came across this JQuery plugin in my quest to find the same.

Github

Demo

Upvotes: 0

Fresheyeball
Fresheyeball

Reputation: 30015

Contrary-wise. You could wrap the text in an interior DIV, measure its width with JavaScript. Test if that width is wider than the parent DIV. Get the current font size, and incrementally move it down 1px at a time until inner DIV's width is less than or equal to the outer DIV's width.

Upvotes: 3

Steve Wellens
Steve Wellens

Reputation: 20620

Short Answer: You don't.

You would have to try a size, render it, see if it fits, try another size, render it see if it fits, etc. Then you have to handle the case where the calculated font size is so small no one can read the text.

There are other options, if the text doesn't fit, add an ellipsis (...) to the end of the text, when you mouse over it, the div could expand, you could use a popup window or tooltip with the full text, or put the full text in a larger area of the screen.

Find another way.

Upvotes: 0

Related Questions