How to Center a <div> on the Screen Using jQuery

There is a way to center a <div> element to the middle of a page using only jQuery.

The code snippet below shows the way to create a function that you can add to your scripts to center the <div> element:

<!DOCTYPE html>
    <script src=""></script>
    <style> {
        width: 400px;
        height: 300px;
        border: 2px solid green;
        position: relative;
        top: 10px;
        left: 10px;
      div.myclass {
        width: 50px;
        height: 50px;
        color: white;
        background: green;
        border-radius: 4px;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
    <div class="box">
      <div class="myclass">Box</div>
      $(document).ready(function() {
 = function(parent) {
            if(parent) {
              parent = this.parent();
            } else {
              parent = window;
              "position": "absolute",
              "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
              "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
            return this;

To use the above function, you should choose the <div> element to center and pass it through your new function:


You should use this.outerHeight() and this.outerWidth(); otherwise, if the object has a padding or border, it will end up off-center.

The jQuery solution can be a perfect solution to center the <div> element if CSS isn’t working.

The .outerHeight() and .outerWidth() Methods

The .outerHeight() and .outerWidth()methods get the height and width (including padding, border, and margin) for the first element in the group of matched elements or sets the outer height and width of every matched element respectively. If two method is called on an empty group of elements, they will return undefined.