After @Darkwater suggested a CSS solution, I developed a jQuery plugin that still utilizes CSS for quick reuse on multiple objects.
To create a new method in jQuery called center
:
$.fn.center = function() {
this.css("position","absolute").css("z-index","5000")
.css("top","50%").css("left","50%")
.css("margin",(-(this.height()/2))+"px 0 0 "+(-(this.width()/2))+"px");
return this;
};
Simply bind it to your object (such as your alert div#message
) right after the .show()
method:
$("#message").show().center();
This will center the div
both vertically and horizontally.
NOTE: Remember to call the center()
method immediately after the show()
or any similar method that displays the element on the DOM, as jQuery may not handle hidden elements properly.