Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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?

like image 495
Justin808 Avatar asked Aug 17 '11 23:08

Justin808


2 Answers

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
}
like image 72
FlavorScape Avatar answered Oct 17 '22 03:10

FlavorScape


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.

like image 44
Fresheyeball Avatar answered Oct 17 '22 01:10

Fresheyeball