Reputation: 767
My objective is to make my text take as much of the space within a container as possible without overflow. If there are only a few words, they would have a very large font size, inversely if there are several words it would result in a smaller size that still takes as much of the containers area as possible.
So if I had this HTML
<div id="container">
<h1 class="textFill">Make this fit as large as possible in the container</h1>
</div>
and the container was 400 by 300px
#container {
width: 400px;
height: 300px;
border: 1px solid blue;
}
I would want the text to fill the entirety of that space. So far I have this script.
function textFill() {
$(".textFill").each(function() {
var
$text = $(this),
$parent = $text.parent();
var
textW = $text.width(),
parentW = $parent.width(),
ratio = parentW / textW;
var
originalSize = parseFloat($text.css('font-size')),
newSize = originalSize * (1 * ratio);
$text.css("font-size", newSize);
});
}
Here it all is in a http://jsfiddle.net/nz7h2858/41/
Upvotes: 0
Views: 165
Reputation: 35670
I would increase the font size until the element goes beyond its parent's bounds.
Then decrease the font size by one.
textFill();
$(window).resize(textFill);
function textFill() {
var tf= $('.textFill');
for(var i = 1 ; ; i++) {
tf.css('font-size', i);
if(tf.outerHeight(true) > tf.parent().innerHeight() ||
tf[0].scrollWidth > tf.width()
) {
break;
}
}
tf.css('font-size', i-1);
}
Upvotes: 1
Reputation: 1105
http://jsfiddle.net/nz7h2858/42/
This seems to be working a majority of the time. Occasionally some text will go out of bounds, but only slightly. Hopefully it's enough to get you started!
Things to notice:
.textFill {
display: inline;
}
Because h1 is a block element, it defaults to the full width of it's parent. So your ratio for width would always be 1:1.
Secondly, you need to also take into consideration the height. So:
textW = $text.width(),
textH = $text.height(),
parentW = $parent.width(),
parentH = $parent.height(),
ratio = (parentW + parentH) / (textW + textH);
Upvotes: 0