Need to center an object whose width changes depending on the browser window. Usually I’d use css with top and left positions set to 50% with a negative margin equal to half the width and height, but obviously that wouldn’t accomodate this need.
I thought my jQuery function would work… but no bueno. am i missing something in CSS?
Thanks!
http://jsfiddle.net/danielredwood/EbkLg/2/
Here’s the CSS
#t {
width:25%;
height:25%;
background:red;
}
JavaScript
$(window).resize(function(){
resizenow();
});
function resizenow() {
var browserwidth = $(window).width();
var browserheight = $(window).height();
$('#t').css('left', (browserwidth - $(this).width())/2).css('top', (browserheight - $(this).height())/2);
});
In your JSFiddle that you linked to you use
$(this).width():But when the function resizenow() is called,
this == window. If you replace$(this)with$("#t")it works fine, as this JSFiddle shows: http://jsfiddle.net/jackfranklin/F2tR3/1/Within the
css()function of jQuery, the value ofthisis not set to the element whose style(s) you are changing, hence why your original code didn’t work.