Automatically adjust font size to fit in fixed form div

Here is the fiddle I work in:

http://jsfiddle.net/LbUFg/

Html code:

<div class="body"> <div class="variation1 font700 green1"> <h2> sample <span class="divider"> arrowshape </span> </h2> </div> <div class="clear"></div> <div class="variation2 font700 green2"> <h2> as the text increases the font size must decrease but the block height must remain same <span class="divider"> as the text increases the font size must decrease but the block height must remain same </span> </h2> </div> <div class="clear"></div> <!-- OTHER HTML --> </div> 

I want to adjust the text so that it fits into the div without changing the size (size) of the indicated block of arrows (the size of the text can change, but not the size of the block). The arrow block should look like a sample arrow, and Im the problem, as shown in option 2. Can someone please help me with this?

+4
source share
3 answers

try the jquery FITTEXT plugin , it will help you

+2
source

You will need to use javascript. CSS itself cannot handle this.

For a bad example:

 $(".font700").each(function(i, obj) { newSize = $(obj).text().length; newSize = 64 - newSize; newSize = (newSize < 10) ? 10 : newSize; $(obj).css("font-size", newSize + "px"); }); 

Jsfiddle

By the way, there will be better solutions than that. It just shows that this is possible with javascript (jQuery in particular). You can probably find some plugins, such as FitText , that can solve many of these problems for you.

(Thanks to Grim for the link)

+1
source

For those who don't like plugins like FitText, I just played and calculated the font size so that it fit into the contained element, looking at the current average letter width (complexity: a few lines that are resolved right away, temporarily changing the CSS width) HTML

 <div><h1><a><span>Title</span></a></h1></div> 

And jQuery:

 $("h1").each(function() { var l = $(this).text().length; var w = $(this).prop("offsetWidth"); //clientWidth doesn't always work var old_pos = $(this).find("a").css("position"); var old_w = $(this).find("a").css("width"); $(this).find("a").css("position", "absolute"); $(this).find("a").css("width", "1000px"); var w2 = $(this).find("span").prop("offsetWidth"); var h2 = $(this).find("span").prop("offsetHeight"); var c = 1.2*(w2/h2)/l; // Current proportion of font width, 1.2 is constant var fontsize = w/l/c; fontsize = (fontsize<10)?10:fontsize; //limit min //$(this).append(" "+c+"/"+fontsize); //test //Set font size to fill width of parent element $(this).css("font-size",fontsize+"px"); $(this).find("a").css("position", old_pos); $(this).find("a").css("width", old_w); }); 

This resizes my fonts in a masonry style grid

0
source

Source: https://habr.com/ru/post/1498415/


All Articles