user713813 user713813 - 2 months ago 6
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
http://jsfiddle.net/k3ugj74e/4/

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



$.fn.center = 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 ='https://www.google.com/logos/doodles/2016/googles-18th-birthday-5661535679545344-hp.gif'

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

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

//this works
//$("#target").text('hi');

$("#target").center(true);

Answer

This code always works for me:

$('#yourimage').css({'top':'50%','left':'50%','margin':'-'+($('#yourimage').height() / 2)+'px 0 0 -'+($('#yourimage').width() / 2)+'px'});