Using jQuery to center a DIV on the screen

By : Craig

How do I go about setting a <div> in the center of the screen using jQuery?

By : Craig


Please use this:

        left: ($(window).width() - $('.className').outerWidth())/2,
        top: ($(window).height() - $('.className').outerHeight())/2

// To initially run the function:
By : satya

Normally, I would do this with CSS only... but since you asked you a way to do this with jQuery...

The following code centers a div both horizontally and vertically inside its container :

            .wrap("<div class='center-outer-container'></div>")
            .wrap("<div class='center-inner-container'></div>");
body {
    margin : 0;
    background: #ccc;

.center-outer-container {
    position : absolute;
    display: table;
    width: 100%;
    height: 100%;

.center-inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
<script type="text/javascript" src=""></script>
<div id="target">Center this!</div>

(see also this Fiddle)

You could use the CSS translate property:

position: absolute;
transform: translate(-50%, -50%);

Read this post for more details.

By : Fred K

This video can help you solving your question :)
By: admin