Setting the height of a DIV dynamically


In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.

I need an auto-height for the object. The DIV starts about 300px from the top screen, and it's height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV.

My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me?

Edit: The DIV houses a control that does it's own overflow handling (implements its own scroll bar).

By : 1kevgriff


document.getElementById('myDiv').style.height = 500;

This is the very basic JS code required to adjust the height of your object dynamically. I just did this very thing where I had some auto height property, but when I add some content via XMLHttpRequest I needed to resize my parent div and this offsetheight property did the trick in IE6/7 and FF3

What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute positioning:

div {
  position: absolute;
  top: 300px;
  bottom: 0px;
  left: 30px;
  right: 30px;

This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom. Add an overflow:auto; to handle cases where the content is larger than the div.

Edit: @Whoever marked this down, an explanation would be nice... Is something wrong with the answer?

Simplest I could come up...

function resizeResizeableHeight() {
    $('.resizableHeight').each( function() {
        $(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css('padding-top') ) ) ) )

Now all you have to do is add the resizableHeight class to everything you want to autosize (to it's parent).

By : RawBits

This video can help you solving your question :)
By: admin