Hi can someone please tell me how to position an image in the centre of the screen using javascript?
Would I get the screen height and divide by 2? How would I get the screen height?
Thanks!
Hi can someone please tell me how to position an image in the centre of the screen using javascript?
Would I get the screen height and divide by 2? How would I get the screen height?
Thanks!
Making a Google search wouldn't hurt...
Centering with CSS:
http://www.bluerobot.com/web/css/center1.html
http://www.spanish-translator-services.com/espanol/t/007/center.html
http://simplebits.com/notebook/2004/09/08/centering/
Centering with javascript (jQuery):
Really, CSS is the best way to do this (as per Sebastián's answer), and if you have to use JS then go for jQuery. However you asked for a javascript solution so you'll find one below.
Really the only two reaons I can see js being necessary are:
Anyways... enjoy:
Usage:
imgToMiddle('imageid');
Note that 'imageid' is the id of the image you want to place in the screen's center. The function modifies the image's css properties to place it in the middle of the screen.
Code:
//viewport width/height code from here: http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
function imgToMiddle(imgid){
function viewportWidth(){
var viewportwidth;
if (typeof window.innerWidth != 'undefined'){
viewportwidth = window.innerWidth;
}
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
viewportwidth = document.documentElement.clientWidth;
}
else{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
}
return viewportwidth;
}
function viewportHeight(){
var viewportheight;
if (typeof window.innerWidth != 'undefined'){
viewportheight = window.innerHeight;
}
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
viewportheight = document.documentElement.clientHeight;
}
else{
viewportheight = document.getElementsByTagName('body')[0].clientHeight;
}
return viewportheight;
}
var img=document.getElementById(imgid);
img.style.position="absolute";
img.style.left=viewportWidth()/2-img.width/2;
img.style.top=viewportHeight()/2-img.height/2;
}