April 5, 2012

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

Question by Vinay

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

Answer by Elliot Bonneville

$("#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
});

Answer by Starx

Using jQuery

$("img").css({
  top: ($(window).height()-$("img").height())/2,
  margin: '0 auto'
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!