Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate div height given a known width?

Tags:

javascript

css

I have a div that contains a picture and some text (the image is of the variable size and the text is of the variable length).
Is there any way to calculate the height required to fit all the div content, given that the exact width is predefined?

UPD getting same wrong result when using $(document).ready()

document.addEventListener("DOMContentLoaded", function ()
{
		var div = document.getElementById("Content");
		var res = document.getElementById("Result");

		res.innerHTML = div.offsetHeight; // incorrect - returns 252 while the real height is 360 (Firefox, Chrome)
});
div
	{
		width: 400px;
	}

	img
	{
		float: left;
		margin: 0.5em;
}
<div id="Content">

	<img src="https://picsum.photos/id/82/200/150" />

	Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Orci phasellus egestas tellus rutrum. Tempor nec feugiat nisl pretium fusce. Cras pulvinar mattis nunc sed blandit libero volutpat sed cras. Purus sit amet luctus venenatis lectus magna fringilla urna. Ut tristique et egestas quis. Mauris cursus mattis molestie a iaculis at erat pellentesque adipiscing. Iaculis eu non diam phasellus vestibulum lorem sed risus ultricies. Semper quis lectus nulla at. Augue interdum velit euismod in. Amet aliquam id diam maecenas ultricies mi eget. Scelerisque viverra mauris in aliquam sem fringilla ut morbi. Et egestas quis ipsum suspendisse. Et malesuada fames ac turpis. Fermentum iaculis eu non diam phasellus vestibulum lorem sed.

</div>
<br/>
<span id="Result"></span>
like image 596
user626528 Avatar asked Nov 27 '19 17:11

user626528


4 Answers

To accurately determine the height of the div and the image. This is because the image will likely finish loading last - if the height of the container is checked before the image is loaded, it will return height without taking the image height into consideration.

A listener should be added to the image so it checks the height once the image loads.

img.addEventListener('load', onLoad);

Because the styling is simple, offsetHeight and clientHeight should work but to include the entire element (with border and margin) use scrollHeight as described by Element.scrollHeight on MDN web docs

The resulting code:

<div id="Content">
    <img id="Image" src="https://picsum.photos/id/82/200/150" />
    ...
</div>
<br/>
<span id="Result"></span>
<script>
    var img = document.getElementById("Image");

    function onLoad() {
        var div = document.getElementById("Content");
        var res = document.getElementById("Result");

        res.innerHTML = div.scrollHeight;
    }

    img.addEventListener('load', onLoad);
</script>

The whole example is in a CodeSnadbox here:

Edit calculate div height - known width - JS

like image 173
Seth Corker Avatar answered Sep 22 '22 01:09

Seth Corker


You have to use window.onload instead.

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. ref

In your case you need to wait for the image and not only the DOM.

window.onload = function() {
  var div = document.getElementById("Content");
  var res = document.getElementById("Result");

  res.innerHTML = div.offsetHeight; 
};
div {
  width: 400px;
}

img {
  float: left;
  margin: 0.5em;
}
<div id="Content">

  <img src="https://picsum.photos/id/82/200/150" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Orci phasellus egestas tellus rutrum. Tempor nec feugiat nisl pretium fusce.
  Cras pulvinar mattis nunc sed blandit libero volutpat sed cras. Purus sit amet luctus venenatis lectus magna fringilla urna. Ut tristique et egestas quis. Mauris cursus mattis molestie a iaculis at erat pellentesque adipiscing. Iaculis eu non diam phasellus
  vestibulum lorem sed risus ultricies. Semper quis lectus nulla at. Augue interdum velit euismod in. Amet aliquam id diam maecenas ultricies mi eget. Scelerisque viverra mauris in aliquam sem fringilla ut morbi. Et egestas quis ipsum suspendisse. Et
  malesuada fames ac turpis. Fermentum iaculis eu non diam phasellus vestibulum lorem sed.

</div>
<br/>
<span id="Result"></span>
like image 44
Temani Afif Avatar answered Sep 22 '22 01:09

Temani Afif


I am not sure I completely understand your question, but you can use javascript to calculate the height of a div.

var height = document.getElementsByTagName('div').offsetHeight;
like image 38
Armedin Kuka Avatar answered Sep 21 '22 01:09

Armedin Kuka


I know that you are asking to resize the div once the image loads to make the div taller, but just as a side comment, do you know/have you tried background-size: contains?

As specified by MDN:

The contain value specifies that, regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.

The cover value:

The cover value specifies that the background image should be sized so that it is as small as possible while ensuring that both dimensions are greater than or equal to the corresponding size of the container. Try resizing the example below to see this in action.

When combined with background-position I think it can be really useful

like image 29
Jenaro Calviño Avatar answered Sep 20 '22 01:09

Jenaro Calviño