Adam Adam - 17 days ago 5
CSS Question

How to dynamically change the size of a div depending on the amount of content

I'm using absolute positioning for a site. Users have profiles and amount of text they write will vary.

How can I update a

div
elements' height dynamically depending on the amount of text that is being shown, ie. change the
div
height to fit the content dynamically.

<div class="profileContainer">
<h3 class="profileText">
Here is the text - this could be 1000px height plus
</h3>
</div>


I know the jQuery
height()
method but I'm not sure how to calculate what number to give it - ie. how to find out the height of the text.

Answer

On page load (or after updating the h3 element if you have some kind of AJAX request being made) you simply need to set the height of the #profileContainer equal to the height of #profileText.

Try this:

$("#profileContainer").height($("#profileText").height());

This is of course assuming that you have set a specific height for the container div in CSS. If you haven't, then the content of the h3 will automatically cause the container to grow as required.

Comments