ben
ben

Reputation: 29817

Adding child elements (divs) to a parent element (div), how can I stop each child affecting the top value of the child after it?

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.

Upvotes: 0

Views: 6730

Answers (2)

Matt Gibson
Matt Gibson

Reputation: 38238

You should be using absolute positioning. Set the positioning of the canvas div to relative (e.g. <div id="canvas" style="position: relative;"></div>), and set your child divs to absolute, i.e.:

$(function() {

var canvas = $('#canvas');
canvas.append('<div id="1"></div>');
$('#1').addClass('ui-boxer')
                .css({ border: '1px solid white',
                       background: 'orange',
                       padding: '0.5em',
                       position: 'absolute',
                       '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: 'absolute',
                       'z-index': 100,
                       left: '50%', top: '10%',
                       width: '20%', height: '50%'});
});

Upvotes: 3

Starx
Starx

Reputation: 79069

Changed the position to absolute.

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

Upvotes: 4

Related Questions