Dynamically resize div to fit dynamic content?

I have a container called div that contains dynamically generated content (paragraphs) through javascript. The problem is that paragraphs are not shown on the div after they go outside the container. To solve this problem, I tried overflow, but just added x, y scrollbars.

What I'm trying to do is increase the height of the container after adding each paragraph added, that is, when a paragraph is added to a container with a height of 20 pixels, the container increases the height to another 40 pixels for the next paragraph.

HTML

<div class="container"></div> <a href="#" id="add">Add content</a> 

CSS

 .container { width: 120px; height: 20px; display: inline-block; margin-left: auto; margin-right: auto; /* overflow: auto; */ //As aforementioned, I'm not in favour of scrollbars background-image: url('http://i.imgur.com/dfzk0TW.png'); } 

Javascript

 $(function () { $('#add').on('click', function () { $('<p>Text</p>').appendTo('#container'); }); }); 

Any suggestions? Thanks!

+6
source share
2 answers

Try this code

jsfiddle

remove height from css and use below code

 $('<p>Text</p>').appendTo('.container'); 

delete # and put a dot (.)

+6
source

this code will get the height of the div container and add 20px to the div container.

  $(function () { $('#add').on('click', function () { $('<p>Text</p>').appendTo('#container'); heightWithPx = $('#container').css('height'); height = heightWithPx.substr(0,heightWithPx.length-2); newHeight = parseFloat(height)+20; $('#container').css('height',newHeight+'px'); }); }); 
0
source

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


All Articles