How can I autoscale the font size to fit the contents of a div?
14,841
Solution 1
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.
Solution 2
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
}
Related videos on Youtube
Comments
-
Justin808 over 1 year
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?
-
Justin808 about 12 years@sidyll - Yes I know, I have them here to simplify the example. My styles are in a .css file
-
-
Joe Landsman about 12 yearsI agree. Javascript is probably the best bet in this case. A quick Google search revealed the "Text Fill" (plugins.jquery.com/project/TextFill) jQuery plugin which seems to fit the bill.
-
FlavorScape about 10 yearsyou just need to set the em dynamically with JS.
-
Fresheyeball about 10 years@FlavorScape good call, care to make an answer? I will upvote.
-
Drakarah over 9 yearsGreat fun when you have multilanguage menus