Why I am always getting an HTML element’s height as 0?

Creating a basic web page seems pretty easy but many times we end up getting stuck in small unknown errors. I recently came up with one such error with a pretty small solution. However, the problem took time to be diagnosed. So sharing my experience here on how I managed to avoid getting my HTML element’s height as 0 despite assigning it a proper value.

The HTML div I created held the clientHeight of another element. On getting constant 0 values of the height, we assumed the clientHeight method might had deprecated and ended up using multiple more methods to get height of an element. Anyhow, all worked well but the div height still remained 0. Then I started inspecting other CSS properties assigned to the faulty div. This helped me find the error was because of position property.

The main problem

When we assign an element the property, position: fixed, its height gets 0. So when reading an element’s property and assigning it to another div, always read it before assigning a position property to it.

So, the main fault is the order of getting and assigning CSS properties. It seems a small thing, but holds great significance. Therefore, the simple solution is to get the div’s height before assigning it the position property. So we can pass an appropriate value to the other element.

Solution

Therefore, whenever getting and assigning basic CSS properties to a div, keep in note to get the div’s height before assigning its position property. Consider the code snippet and sequence below that should be used when getting and assigning a div with CSS properties. The sequence shown should be followed.

JavaScript Example

The example below shows the correct sequence how position and height property should be used for two divs in JavaScript.

var h2 = div1.clientHeight; 
div1.style.position= 'fixed';
div2.style.height= h2+"px";