Reputation: 586
a simple problem that comes with high frustration levels on my behalf.
I am creating a house. I am dynamically creating 4 rooms (divs) with a width, height and position absolute.
After creating them, I append them with jquery to the only div I have in the html:
<div id="myHouse"></div>
Everything works, except that myHouse doesn't take the height and the width of the rooms I have just created, it just has 0px height. I tried giving it a relative positioning, absolute positioning, static and everything else.
It just seems that the div is empty, however it's not. It has my rooms inside.
What might be the problem?
Upvotes: 0
Views: 264
Reputation: 435
Here is your creation loop updated. Basically, you have to compute the total width and height of your house, like this:
var totalWidth = 0,
totalHeight = 0;
for(i = 0; i<house.rooms.length; i++){
//Generating rooms
var room = '<div class="room" style="width: '+house.rooms[i].width+'px; height: '+house.rooms[i].height+'px; top: '+house.rooms[i].top+'px; left: '+house.rooms[i].left+'px; background-color:'+house.rooms[i].floor+'"></div>';
totalWidth = Math.max(totalWidth, parseFloat(house.rooms[i].width) + parseFloat(house.rooms[i].left));
totalHeight = Math.max(totalHeight, parseFloat(house.rooms[i].height) + parseFloat(house.rooms[i].top));
$('#myHouse').append(room);
};
$('#myHouse').css({ width: totalWidth, height: totalHeight });
As you can see, at each step, we test if the boundaries of the house have to be expanded with the Math.max(x1, x2)
method.
I would recommend updating your data model to use numbers instead of strings for the values, if possible. The parseFloat
method can produce funny results if you don't pass it something potentially numerical.
Also, this method won't take the border into account, but you get the point.
Finally, please note that this solution expects you not to have negative coordinates, of course.
Upvotes: 1
Reputation: 5535
If you use position absolute in your elements than you have to calculate the height of the container. It won't have its height automatically set to accommodate the elements inside if they have position set to absolute.
Upvotes: 0