I have a div element of css width and height, 800×600. I am using javascript to generate three object elements in the div that should be in a diagonal line, touching each other. I am using position:relative, and the left and top css properties to position the object elements. However when I do it this way, there is a horizontal gap between the squares that shouldn’t be there. When I use positon:fixed, they line up how I want it but not inside the div element.
Html of my div element
<div id="Stage" style="background:black;width:800px;height:600px;margin-left:auto;margin-right:auto;overflow:hidden;">
and my javascript
w="w";
level_data =
[
[w,0,0],
[0,w,0],
[0,0,w],
];
function generate(level_data){
for(row=0;row<level_data.length;row++){
for(col=0;col<level_data[row].length;col++){
posx = col*50; posy=row*50;
if(level_data[row][col]=="w"){
entity = document.createElement('object');
entity.style.position = "relative";
entity.style.left = String(posx)+"px"; entity.style.top = String(posy)+"px";
entity.data = "Objects/Sprites/Wall.jpg";
document.getElementById("Stage").appendChild(entity);
}
}
}
}
generate(level_data);
This is what I get: Link1
This is what I want: Link2 but the redsquares inside the big black square instead. What’s the problem?
position: fixedpositions elements relative to the viewport.position: relativegives that result becauseobjectelement probably has some default value forwidhtandheight. You’ll need something like this:When using
position: absolute, the code is supposed to work even without dimensions for theentity. Notice , that when usingposition: relativeyou should not multiply position values withcol, they should be just50px.