Rouge
Rouge

Reputation: 4239

Absolute position issue

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!

Upvotes: 0

Views: 109

Answers (3)

Nick
Nick

Reputation: 9154

When an element is a child of another element, absolute positioning isn't really absolute to the window, it's absolute relative to its parent. If you want a div's top-left corner to be perfectly in place with it's parent's top left corner, then you want it's top and left to be exactly zero pixels away from it's parent. It is only absolute because it ignores all other items that may move it out of place.

Here's a demonstration of that in action

When B is a child of A, for every situation where B needs to be aligned with A, just always set it's left and top to 0.

Upvotes: 0

Philippe Boissonneault
Philippe Boissonneault

Reputation: 3949

Function offset() will give you the offset of the element in the window. What you need is the relative offset of elementA inside its container.

Try position() instead of offset()

Based of the other example: http://jsfiddle.net/dcFXj/

Upvotes: 0

Slava Fomin II
Slava Fomin II

Reputation: 28661

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:

$('#elementB').position({
  my: 'left top',
  at: 'left top',
  of: '#elementA'
});

Also i think it's a good practice to add 'px' to the value of css property, e.g.:

$('...').css({
    left: 100 + 'px'
});

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).

Upvotes: 1

Related Questions