Can we find div height without rendering

Gurusabarish
1 min readOct 24, 2023

--

Probably yes, we can find an HTML element’s width and height for below mentioned scenario.

  • We should know element’s styles like padding, width
  • And also we should know each possible character’s height and width. You can also take average of all character height and width if suitable in your case.

Below example with average height and wight. Here, we take Q character’s height and width as it is one of the largest character. After we have to find maximum characters within specific width. We can find max Line for an element.

function maxCharatersByWidth(divStyles, charaterWidthAndHeight) {
var actualWidth = divStyles.width - (divStyles.paddingLeft + divStyles.paddingRight);
var maxCharacters = (actualWidth)/charaterWidthAndHeight.width;
return Math.ceil(maxCharacters);
}

var charaterWidthAndHeight = {};
var divElem = document.createElement("div");
divElem.innerText = "Q";
document.body.appendChild(divElem);
charaterWidthAndHeight.height = divElem.offsetHeight;
charaterWidthAndHeight.width = divElem.offsetWidth;
document.body.removeChild(divElem);

var divStyles = {
width : 100,
paddingLeft : 20,
paddingRight : 20
};
var divText = "To find div element's height without rendering";
var maxCharaters = maxCharatersByWidth(divStyles, charaterWidthAndHeight);
var maxLine = Math.ceil(divText.length/maxCharaters);
var divHeight = (maxLine * charaterWidthAndHeight.height) + divStyles.paddingTop + divStyles.paddingBottom;
console.log("div element's height is", divHeight);

This approach can offer a rough estimate of an element’s height without rendering, it may not be entirely accurate due to various factors like font variations, text wrapping, and unaccounted CSS properties.

--

--

Gurusabarish
Gurusabarish

Written by Gurusabarish

Hey there!, I’m Gurusabarish. I build things for the web. A passionate web app developer. I tend to make use of modern web technologies to build websites.

No responses yet