I’m trying to absolutely position some floated divs using this code:
$(function() {
$('#wrapper div').each( function( index, item ) {
alert( $(this).position().left );
$(this).css({position:'absolute', top:$(this).position().top, left:$(this).position().left});
});
});
What I can’t figure out is why when I set position:absolute $(this).position() always returns {top:0, left:0}. How can I get the proper coordinates and set the position to absolute?
I’ve set up a jsfiddle to illustrate this http://jsfiddle.net/SxJCb/4/
Short answer:
Set only
topandleftfor all thedivs. Once that has been done, then setposition: absoluteon all of them.See: http://jsfiddle.net/thirtydot/SxJCb/6/
Long answer: (an explanation of what’s going on)
All the
divs are floated. As you had it, eachdivwas being removed from normal flow by being set toposition: absolute, so all the subsequentdivs shifted back a place. So, the seconddivmoves to where the first one was, etc.Here’s a slow motion demo of what was happening: http://jsfiddle.net/thirtydot/SxJCb/7/