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>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
    <style>
      div.box {
        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;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="myclass">Box</div>
    </div>
    <script>
      $(document).ready(function() {
          jQuery.fn.center = function(parent) {
            if(parent) {
              parent = this.parent();
            } else {
              parent = window;
            }
            this.css({
              "position": "absolute",
              "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
              "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
            });
            return this;
          }
          $("div.myclass:nth-child(1)").center(true);
        });
    </script>
  </body>
</html>

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

$(element).center();

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.