Css Absolute Positioning Elements Inside A Div
Solution 1:
Add
position:relative
To the wall div
Solution 2:
I am working on a website that does exactly that (sorry for the non-english stuff):
http://moveit.canassa.com/cartao/4/
The link is now broken but here is a jsFiddle that shows what I am talking about:
http://jsfiddle.net/canassa/Z9N3L/
The "toy" div is using a position absolute:
.toy{
width: 100px;
height: 25px;
position: absolute;
z-index: 0;
}
The problem with the position absolute is that the toy will be relative to page and not the "wall" container, in order to fix that you must make the wall container relative:
#wall{
position: relative;
overflow: hidden;
}
The overflow:hidden is also a nice trick that I found. It makes the draggable objects go "under" the wall container.
There is no big secret to make it draggable, using jQuery:
// Creates a toy div inside the wall
$(MV.wallId).append('<div class="toy" id="' + this.getId() + '"></div>');
box = this.getBox(); // return the "toy" that I've just created.
$('#' + this.getId()).draggable(); // make it draggable
Solution 3:
This would be a lot easier if you just used the jQueryUI .draggable()
. It doesn't require the elements to be positioned.
If you're dead set on using this plugin, then you have the right idea. Let the elements flow into place and then calculate their position and set position: absolute
and whatever the left
and top
end up being at runtime.
Set the .wall
to be position: relative
. Then:
var tPos;
$('.toy').each(function(index) {
tPos = $(this).position();
$(this).css({
left: tPos.left,
top: tPos.top
});
};
$('.toy').css({
position: absolute
});
The height of the .wall
and the width of each .toy
collapse when the toys are absolutely positioned but you can just add a few more lines to get/set their width and height in the above .each
loops.
This obviously doesn't work if new toys can be added dynamically without a page reload as you suggest. To handle that you could switch them back to position: relative
, add the new one, get the position of the new one in the flow, then set the position and switch back to position: absolute
. Any elements that had been dragged out of place would be gaps in the flow, but I don't see any easy way around that.
Solution 4:
the element in that the absolute should be positioned, must have the style position:relative. (must be a parent of the target element)
Solution 5:
The container div
for every .toy
must have position:relative
set. That way, the position 0 for its children elements becomes its top left corner. Like this:
<divclass="parent"><divclass="child">Blah.</div><divclass="child">Blah.</div></div>
And:
.parent {
position: relative;
}
.child {
position: absolute;
left: 10px; /* This is 10 pixels from the parents left side */top: 10px; /* This is 10 pixels from the parents top side */
}
Good luck.
Post a Comment for "Css Absolute Positioning Elements Inside A Div"