Dynamically resize container to fit text

2020-06-21 04:51发布

There are many jQuery plugins that let you resize a text to fit a container. But how can you dynamically change the width/height of a div container to fit the text inside of it?

Below an example. As you can see the text is currently overflowing the div. How can you programatically resize the container div to fit the text independent of the font size and content?

   <!DOCTYPE html>
   <html>
   <body>
   <div id="container" style="width:100px; height:100px;border:1px solid red; overflow: hidden;">
   <p style="font-size:40px;">This is the text</p>
   </div>
   </body>
   </html>

3条回答
Bombasti
2楼-- · 2020-06-21 05:37

It should be done with css but this is how to do it in JS/jQuery

$('#container').each(function(){
    var inner = $(this).find('p');
    $(this).height(inner.outerHeight(true));
    $(this).width(inner.outerWidth(true)); 
});

http://jsfiddle.net/2CDt5/2/

Alternative solution is to set the width height and display property with the css method

$('#container').css({'width':'auto','height':'auto','display':'table'})

http://jsfiddle.net/7yH2t/

查看更多
家丑人穷心不美
3楼-- · 2020-06-21 05:40

Remove width and height, add display:table;

查看更多
Emotional °昔
4楼-- · 2020-06-21 05:45

You could decide how do you want the box to fit the text - in width or in height.

If you want width, change

width: auto

If you want height, change

height: auto

JSFiddle: http://jsfiddle.net/39e7z/

查看更多
登录 后发表回答