November 12, 2010
Adding child elements (divs) to a parent element (div), how can I stop each child affecting the top value of the child after it?
Question by ben
In this jQuery code, I am dynamically adding boxes to the canvas div like this:
var canvas = $('#canvas');
canvas.append('<div id="1"></div>');
('#1').addClass('ui-boxer')
.css({ border: '1px solid white',
background: 'orange',
padding: '0.5em',
position: 'relative',
'z-index': 100,
left: '1%', top: '10%',
width: '40%', height: '50%'});
canvas.append('<div id="2"></div>');
$('#2').addClass('ui-boxer')
.css({ border: '1px solid white',
background: 'orange',
padding: '0.5em',
position: 'relative',
'z-index': 100,
left: '50%', top: '10%',
width: '20%', height: '50%'});
The boxes are created okay, but the top position of the second box is wrong. It’s 10% (like the first box), but it’s clearly not working correctly. I think the presence of the first child is affecting it? How can I set the top value so that it is based of the parent element (the canvas div) and not the child element before it? Thanks for reading.