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.

Answer by Starx

Changed the position to absolute.

Check this
http://jsfiddle.net/heQFB/1/

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!