center div using jquery

How to Center Div Using jQuery

Often web developers need to center a DOM element horizontally or vertically on their screens. It can be tricky to do this using CSS or plain JavaScript. In this article, we will learn how to center div using jQuery. You can also use this approach for other DOM elements.


How to Center Div Using jQuery

Let us say you have the following div on your page.

<div id='myDiv'>...</div>

First, of all set the position CSS attribute of this div to be absolute.

$('#myDiv').css("position","absolute");

Next, we center it vertically, with the following command.

$('#myDiv').css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");

In the above code, we take a difference between screen height (window.height) and div’s height and divide it by 2. Then we add an offset equal to position of vertical scroll bar to it to calculate the vertically center position of div.

Similarly, we use the following command to horizontally center the div.

$('#myDiv').css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");

In the above code, we take a difference between screen width (window.width) and div’s width and divide it by 2. Then we add an offset equal to position of horizontal scroll bar to it to calculate the horizontally center position of div.

If you want, you can also create a function out of these commands as shown below.

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;
}

Once you define this function, you can easily call it on any DOM element of your page.

$(element).center();

Here is an example.

$('#myDiv').center();

In this article, we have learnt how to center div using jQuery. You can use this to horizontally and vertically center DOM element in jQuery. If you want to center it only horizontally or vertically but not both ways, use only one of the two centering commands mentioned above, as per your requirement.

Also read:

How to Select Element by Data Attribute in jQuery
How to Find Table Was Last Updated in MySQL
How to Truncate All Tables of Database in MySQL
How to Get Primary Key of Newly Inserted Row in PostgreSQL
How to Get Primary Key of Newly Inserted Row in MySQL

Leave a Reply

Your email address will not be published.