Checking a text element's width (based on font-size) against its parent container
css, font-size, javascript, jquery
Solution
There may be a method that's not as crazy, but this should be as precise as possible. Essentially, you have a div that you use to measure its width and incrementally increase the text content until it exceeds the width of the target div. Then, change the target div's `<p>`'s font size to the measuring div's minus 1:
http://jsfiddle.net/ExplosionPIlls/VUfAw/
var $measurer = $("<div>").css({
position: 'fixed',
top: '100%'
}).attr('id', 'measurer');
$measurer.append($("<p>").text($("p").text()));
$measurer.appendTo("body");
while ($measurer.width() <= $("#content").width()) {
$("#measurer p").css('font-size', '+=1px');
console.log($("#measurer").width());
}
$("#measurer p").css('font-size', '-=1px');
$("#content p").css('font-size', $("#measurer p").css('font-size'));
$measurer.remove();
Problem
I come to you with a tricky question: Imagine you have the following basic structure: ``` <div><p>hello</p></div> ``` Now assume that div has `display:block; and width:200px;`. Using javascript, how would you check what font-size gives you a 'hello' as big as possible without horizontal overflow (in the case of one word) or jumping to a 2nd line in case of a sentence or group of words? I can't think of a way to measure the space occupied by text so that it can then be checked against that of the parent container, let alone checking if an element is overflowing or linejumping. If there is a way, I'm sure this is the right place to ask.