Adam
Adam

Reputation: 20882

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.

Upvotes: 1

Views: 2534

Answers (3)

Ashwini Agarwal
Ashwini Agarwal

Reputation: 4858

You can do this with css...

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

Upvotes: 0

Gunjan Karun
Gunjan Karun

Reputation: 795

If your purpose is to show all the contents then the following css will do the trick.

 div.profileContainer {height:auto; width:300px;}

That way the container will automatically grow in size to fit the contents and the width will be restricted to 300px

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 2

Related Questions