Positioning an element w.r.t the window using jquery

Go To StackoverFlow.com

0

var wdt = document.body.offsetWidth/2.6

var hgt = document.body.offsetHeight/4

$("#element").offset({left:wdt, top:hgt})

what i am trying to do is position the image(#element) relative to the body..ie to the center with respect to the window ... for different Browser/window sizes/screen....irrespective of any screen.

Is this valid.. or are there any more..?

2012-04-05 17:59
by Vinay
With regard to your variable names, you should keep them fairly verbose; 'wdt' means nothing to any other developers besides you, whereas 'width', though only a few characters longer, is much more readable - Elliot Bonneville 2012-04-05 18:09
Agreed. That makes sense.. : - Vinay 2012-04-05 18:24


1

$("#element").css({left:50%, top:50%});

or

$("#element").css({left:window.innerWidth/2.6, top:window.innerHeight/4});

Should do it. Or better yet, in your CSS file:

#element {
    left:50%;
    top:50%;
}

Be aware that this will position your element based on the upper left corner, so it won't appear to be in the exact center. To account for that, you could do this (keeping the above CSS):

$("#element").offset({
    left:-$(this).css("width")/2,
    top:-$(this).css("height")/2
});
2012-04-05 18:01
by Elliot Bonneville
This cannot position the element correctly, as element size is not accounted fo - Starx 2012-04-05 18:03
I noted that, and I'm editing to account for it - Elliot Bonneville 2012-04-05 18:04
The image is Spinner Loading...image for light box..of 150x80 size.. - Vinay 2012-04-05 18:23
@Vinay: See the bottom of my answer, it should take care of everything for you automatically - Elliot Bonneville 2012-04-05 18:24
Cool, Will implement this and let u know.. :) Appreciate your help all : - Vinay 2012-04-05 18:28
@Vinay: No problem, glad I could help. If it works for you, accept and upvote my answer please! = - Elliot Bonneville 2012-04-05 18:28
That goes without saying. Cheers : - Vinay 2012-04-05 18:32


0

Using jQuery

$("img").css({
  top: ($(window).height()-$("img").height())/2,
  margin: '0 auto'
});
2012-04-05 18:02
by Starx
Don't forget he wants the top in the center as well. Or, to be precise, 25% of the way down - Elliot Bonneville 2012-04-05 18:05
@ElliotBonneville, How about the update - Starx 2012-04-05 23:16
Don't know what you're talking about-- I did update my answer - Elliot Bonneville 2012-04-06 01:22
Ads