Arun Kumar Arun Kumar - 1 year ago 125
CSS Question

marginTop not working in javascript

I was trying to run a script to draw a pattern of squares within squares. So I did this.

var bodyNode = document.getElementsByTagName("body")[0];
var width = 600, height = 600;
var top = 10, left = 10;
while(width > 30)
var divNode = document.createElement("div"); = "absolute"; = left; = top; = width; = height; = randomColor();


width -= 10;
height -= 10;
top += 10;
left += 10;


function randomColor()
var color = "#";
for(var i =0; i < 6; i++)
var number = Math.floor(Math.random() * 10);
color += number;
return color;

But the properties which get added to the div in the runtime are: {
position: absolute;
margin-left: 260px;
width: 350px;
height: 350px;
background: rgb(88, 88, 5);

I am trying to achieve this effect but I get a different pattern as shown in the image below.

What am I missing?

the output of my script

P.S.: I am not using Jquery.

Answer Source

Thanks to Atul for pointing out my mistake.

I figured it out to get the desired effect. Since I have made the position of the div to be absolute, it is enough to set the position using style.direction. = top + "px"; = left + "px";

And in each iteration of the loop, I have decremented the width and height by 10 which should be 20. This is because only when I set the width of the inner div to be less than 20 of the outer div, both the inner and outer div appear as a whole. Otherwise only the left and top borders show up.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download