I am trying to setup a element B’s absolute position on top of element A. I have
var left = $('#elementA').offset().left;
var top = $('#elementA').offset().top;
---------------------------
| ----------- |
| |o | |
| | | |
| | | |
| | | |
| ----------- |
|--------------------------
o means my elementA.
I want to put element B the same location as element A
$('elementB').css({ position:'absolute',
top:top,
left:left})
---------------------------
| ----------- |
| |o | |
| | b | |
| | | |
| | | |
| ----------- |
|--------------------------
b means my element b
but it turns out like above.
If I set
$('elementB').css({ position:'absolute',
top:0,
left:0})
it would works. but I have many different element B and element A and I can’t use 0 for all of them.
Anyone can help me about this? Thanks a lot!
You can use jQuery UI Position plugin to position any element relative to any other element. See: http://docs.jquery.com/UI/Position
In your case it would be:
Also i think it’s a good practice to add ‘px’ to the value of css property, e.g.:
You should always take into account elements disposition relative to each other as stated above. If parent element is “positioned” then child elements will be positioned not relative to the window, but relative to their parent. If you want more flexibility you can take element B out of the element A (make them siblings).