How to Dynamically Resize Height of Div Elements

By | August 13, 2015


Configuring your div elements to the same height on your web page is a fairly simple task to accomplish with the help of a few lines of JavaScript code. Without help from JavaScript, the divs on the page will have different heights based on the content within them. Setting the height manually is generally not a viable option because predicting the height needed for the content to fit in the div is not going to be known. This is especially true for blog sites where you may have a content and sidebar type of setup. The height of the content div will vary as new blog posts are published.


Webpage Example

The web page in this example, has various components such as a header, content, sidebar, and footer. For the examples shown in this tutorial, the CSS code listed here is applied to the various HTML elements. As you can see, the main and sidebar div are being placed side by side.

CSS Style:

HTML Code:



You will notice that there is a area under the sidebar that has no content. The area is represented by the red “x” in our figure. Since our div elements are not configured with a set height, the div elements will be sized according the content they contain. While we can manually set the height for the divs, this approach will only work well if the divs’ content is static in nature. For a website where the content is dynamic, we cannot set the height manually because we may not be aware of how much content will be placed within the div elements.


Resize Divs Dynamically

We will use a few lines of JavaScript code to resize the div elements so that they share the same height on the page. The results we want to achieve are shown in the following figure. In this case, the sidebar div is resized to match the height of the main div. In the JavaScript code below, we will use a conditional statement to determine which div height is greater and resize the div with the smaller height to match the div with the greater height.



JavaScript Code

Place the following JavaScript code at the bottom of the web page, just before the closing </body> tag.

Give your feedback Please!