How to adapt font size to div size?

There is a div with a fixed height and width. This div contains dynamic content, text content. If the text gets too long, it will “blow” the div. And when the text gets too short, the div will look empty.

So my conclusion would be to make the font larger when the text is shorter and smaller when the text is long.

Never tried this, how to achieve this?

€: since I already use dojo, since the js framework, including jquery or any other structure, is not an option. Of course, thanks for the answers.

+6
source share
5 answers

Create another element inside the div and add some text.

Divide the width of your DIV by an element, multiply by 100, and you have a percentage for the css font size.

You will have to play with the font size on your external DIV to get the shape you need.

+3
source

There are many plugins that can be associated with this. One of them is here .

+3
source

jQuery is probably the easiest option here. Can you use the css function to change the font-size in a field if the height above a certain value? Check out this script (which I tested in Chrome).

 $(function() { $('.text').each(function() { if($(this).height() > 30) $(this).css('font-size', '12px'); }); }); 
+2
source

You can do this with javascript, using string.length to get the length of your string, and then the jquery.css () method to dynamically set the size (http://api.jquery.com/css/), or if you can make some server-side scripts with customization, you can set the size using the inline style before the page loads. The jquery.css method is used here

edit: After editing re dojo, you can use the same basic method, but just set the font size using dojo methods, not jquery. This tutorial looks useful.

+1
source

possibly using jquery

 $(document).ready(function() { var originalFontSize = 12; var sectionWidth = $('...').width(); $('...').each(function(){ var spanWidth = $(this).width(); var newFontSize = (sectionWidth/spanWidth) * originalFontSize; $(this).css({"font-size" : newFontSize, "line-height" : newFontSize/1.2 + "px"}); }); }); 

hope this helped! I post kinda the same question, and the moderator said that this is an off-topic question :)

0
source

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


All Articles