W3docs

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

Read the tutorial and learn the jQuery method of centering the <div> element on the screen. Get a code snippet to add your script for centering the element.

There is a way to center a <div> element relative to its parent container or the viewport using only jQuery.

The code snippet below shows the way to create a function that you can add to your scripts to center the <kbd class="highlighted"> XFI2 </kbd> element:

Javascript add 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 <kbd class="highlighted"> XFI3 </kbd> element to center and pass it through your new function:

Javascript add scripts to center the <div> element

$(element).center();

You should use <kbd class="highlighted">this.outerHeight()</kbd> and <kbd class="highlighted">this.outerWidth()</kbd> 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 <kbd class="highlighted"> XFI4 </kbd> element if CSS isn’t working.

The .outerHeight() and .outerWidth() Methods

The <kbd class="highlighted">.outerHeight() </kbd> and <kbd class="highlighted">.outerWidth() </kbd> 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 these methods are called on an empty group of elements, they will return undefined.