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 divs are being placed side by side.

CSS Style

HTML Code

You will notice that there is an 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 to 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 closingtag.

Dynamically Resizing Height of Div Elements - 17Dynamically Resizing Height of Div Elements - 84