Reputation: 578
I'm trying to set offset (top and left) of an element relative to parent.
I have a container with position relative and the element that i must position with display absolute. How can i set top and left of the absolute element? Offset set the top and left related to document and i didn't need it.
Thanks in advance!
EDIT: this is my code:
var styles = {
width: 200,
height: 200,
position: 'absolute',
top: 10,
left: 20
};
$imgScaledCircle.attr('src', pathimg).css(styles).addClass('active');
It set all proprerties expect top and left. I didn't understand why.
Upvotes: 1
Views: 2897
Reputation: 578
I understand why my code didn't work. I was placing a value stored in a variable:
var coord = $that.attr('coords').split(',');
var styles = {
position: 'absolute',
top: coord[1],
left: coord[0]
};
It didn't work. Maybe because the split method return a string and not a number. If i write this (to force a variable to Number):
var coord = $that.attr('coords').split(',');
var styles = {
position: 'absolute',
top: (coord[1] >>> 0),
left: (coord[0] >>> 0)
};
It add the styles correctly. Thanks at all for the help.
Upvotes: 1
Reputation: 114461
A n element with position:absolute
uses coordinates relative to the first container you find moving up the parent chain that has a position that is either absolute
or relative
. Elements with the default position
attribute (static
) are not considered during this search.
To place an element inside a container positioned at a given pixel inside the container, the container itself should be declared with position: relative
leaving its left
and top
to default.
.container { position: relative; }
.element { position: absolute;
left: 100px;
top: 30px; }
Upvotes: 1
Reputation: 167162
You can use this way:
$(child).each(function () {
$(this).css({
top: $(this).parent().offset().top + 5,
left: $(this).parent().offset().left + 5
});
});
Here child
is the selector for the child element. You can replace the hardcoded 5
to whatever the position you wanna displace.
Upvotes: 1