user1469270
user1469270

Reputation:

jQuery dynamic centering in not working as expected

I'm trying to center a dynamicly sized .nav, within a static .container div. I have the following code:

JSFIDDLE

 $('.nav').css({
     'position': 'fixed',
         'left': '50%',
         'top': '50%',
         'margin-left': -$(this).outerWidth() / 2,
         'margin-top': -$(this).outerHeight() / 2
 });

Can anyone explain why the .nav is not centering within its parent element?

Upvotes: 1

Views: 42

Answers (2)

Lobstrosity
Lobstrosity

Reputation: 3936

2 issues:

  1. As Chris pointed out, $(this) is not .nav. In your example, $(this) is JSFiddle's Result iframe, so you're calling outerWidth/Height on the wrong element.

    I recommend capturing .nav as a local variable (to minimize jQuery selections).

  2. Since .nav is initially position: static, its initial width is 100% of its container. So (and assuming you already fixed #1) outerWidth() in your fiddle would return 500px which would lead to a left margin of -250px.

    .nav's position needs to be set before you call outerWidth() so that its width collapses first. (And its position needs to be set to absolute instead of fixed.)

Both issues fixed in this fiddle: http://jsfiddle.net/8jfkv/13/

Upvotes: 1

Chris Laplante
Chris Laplante

Reputation: 29658

The primary problem is that this doesn't refer to what you think it does. You are still in the same scope when execution reaches these lines:

'margin-left': -$(this).outerWidth() / 2,
'margin-top': -$(this).outerHeight() / 2

so this still refers to what it did before the .css call. For the most part, this only changes (at jQuery's hands) when you are inside a callback to a jQuery function or event.

After fixing that, it sort of works: http://jsfiddle.net/8jfkv/11/, but there is still something off with your calculations.

Upvotes: 3

Related Questions