jhunter_d
jhunter_d

Reputation: 63

How to make an element's height increase with every child added to it

I have a <div> that has children appended to it by a script. These children elements are automatically appended by a PHP script and positioned using position:absolute. I tried to give the parent <div> the style min-height:400px allowing the elements appended to the <div> to increase the parent's height. The only problem is that the height does not increase when I do this. Does anybody know what I can do to fix this?

EDIT: I am not able to use position:relative for positioning my elements. Are there any solutions that allow for position:absolute.

Upvotes: 2

Views: 441

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

Yes you can use position absolute (yeee♥!)

LIVE DEMO TEST CASE

By simply doing:

$(this).height( this.scrollHeight );

or with pure JS:

this.style.height = this.scrollHeight ;

and adding this to your element's CSS:

overflow:hidden;
overflow-y:auto;

Edit:

The demo tested fine in IE10, Firefox, Chrome, Safari, and Opera.

The key point here is setting the overflow value for the x or y axis (whichever dimensions you need the size of) to auto, rather than the default value of visible. Then the scrollWidth or scrollHeight property can be used on the HTML DOM object to get the full size of the element, including any absolutely-positioned descendants.

Odd as it seems, this is entirely consistent with the fact that setting overflow:hidden for a container clips any absolutely-positioned descendants. Apparently, elements with position:absolute aren't quite as "out of the flow" as we've always been told :)

Upvotes: 4

Koen Peters
Koen Peters

Reputation: 12916

You should not use position: absolute for this because stuff that is positioned that way will be pulled out of the normal render flow. This results in the parent not noticing that its content s acually very high. Use position: relative for the child div's. This way the parent will grow automatically.

Upvotes: 0

Related Questions