Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 its 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).

like image 545
1kevgriff Avatar asked Aug 28 '08 18:08

1kevgriff


People also ask

How do I change the height of a div dynamically?

The content height of a div can dynamically set or change using height(), innerHeight(), and outerHeight() methods depending upon the user requirement.

How do I set dynamic height in HTML?

getElementById('myDiv'). style. height = '500px'; . If you have a dynamic height you can use height + 'px' .

How do you calculate dynamic height in CSS?

We use css property height: calc( 100% - div_height ); Here, Calc is a function. It uses mathematical expression by this property we can set the height content div area dynamically.


2 Answers

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?
like image 35
Chris Marasti-Georg Avatar answered Sep 24 '22 00:09

Chris Marasti-Georg


Try this simple, specific function:

function resizeElementHeight(element) {   var height = 0;   var body = window.document.body;   if (window.innerHeight) {       height = window.innerHeight;   } else if (body.parentElement.clientHeight) {       height = body.parentElement.clientHeight;   } else if (body && body.clientHeight) {       height = body.clientHeight;   }   element.style.height = ((height - element.offsetTop) + "px"); } 

It does not depend on the current distance from the top of the body being specified (in case your 300px changes).


EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course.

like image 74
Jason Bunting Avatar answered Sep 23 '22 00:09

Jason Bunting