user713813 user713813 - 1 year ago 49
CSS Question

center a div in center of screen with a background image using jquery

I have a function that adds centering ability to jquery.
it works find when applied to a div with the text.
but when the background is set it doesn't work.
what am I doing wrong?

here is a fiddle demo

<div id='target'></div>

$ = function() {
this.css("position", "absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;


var i =''

var backgroundimage = "url('" + i + "') no-repeat";

//this doesn't
$("#target").parent().css('background', backgroundimage);

//this works


Answer Source

This code always works for me:

$('#yourimage').css({'top':'50%','left':'50%','margin':'-'+($('#yourimage').height() / 2)+'px 0 0 -'+($('#yourimage').width() / 2)+'px'});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download