Fit Cufon texts to its container
Sunday, April 22, 2012
Well, I ran into a situation that my design messed up when the cufon title width passed it’s container width, so I needed to lower the font-size automatically to make it fit into it’s container staying still an one-line title. And I wanted to share here. Here’s the function I wrote:
function Cufon_Fit_Title(element) { var TotalWidth = 0; element.children().each(function() { TotalWidth += $(this).width(); }); if (TotalWidth > element.width()) { element.css("font-size", parseInt(element.css("font-size")) - 1 + "px"); element.css( "padding-bottom", parseInt(element.css("padding-bottom")) + 1 + "px" ); Cufon.refresh(); Cufon_Fit_Title(element); } else { return true; } }
And here’s the important part of it, because jQuery’s $(document).ready() function won’t work well with Cufon texts (insert it anywhere in your document body – and don’t forget to change the selector):
Cufon.DOM.ready(function() { Cufon_Fit_Title($(".title")); });