patternjavascriptCritical
Using jQuery to center a DIV on the screen
Viewed 0 times
divjquerythecenterusingscreen
Problem
How do I go about setting a `` in the center of the screen using jQuery?
Solution
I like adding functions to jQuery so this function would help:
Now we can just write:
Demo: Fiddle (with added parameter)
jQuery.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;
}Now we can just write:
$(element).center();Demo: Fiddle (with added parameter)
Code Snippets
jQuery.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;
}$(element).center();Context
Stack Overflow Q#210717, score: 1086
Revisions (0)
No revisions yet.