admin管理员组

文章数量:1244247

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>

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>
Share Improve this question asked Mar 21, 2014 at 23:54 checkmate711checkmate711 3,4612 gold badges39 silver badges47 bronze badges 6
  • Reverse all the lines in a plugin that does the opposite, and see if it works ? – adeneo Commented Mar 21, 2014 at 23:55
  • How about "height:auto;" ? – urish Commented Mar 21, 2014 at 23:56
  • divs are flexible by default. You should be able to reduce the style to just border:1px solid red; and the div will stretch. – calvin Commented Mar 21, 2014 at 23:57
  • But divs are display block type, so it will be 100% width, height auto – enapupe Commented Mar 21, 2014 at 23:57
  • @enapupe I noticed your answer. You're right, although setting the width as a percentage has better support than display: table;. caniuse./#search=Table%20display Easier and more zen to let the div be a div. :p – calvin Commented Mar 22, 2014 at 0:00
 |  Show 1 more ment

3 Answers 3

Reset to default 5

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/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/7yH2t/

Remove width and height, add display:table;

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/39e7z/

本文标签: javascriptDynamically resize container to fit textStack Overflow