htmljqueryjquery-uidraggablejquery-ui-draggable

How to fix the offset when jquery-ui set center align element draggable?


here's the vertical center align element draggable example:

<html>
<head>
    <style>
        #draggablediv {
            width: 100px;
            height: 100px;
            background-color: yellow;

            position: absolute;
            margin: auto 0;
            top: 0;
            bottom: 0;
        }
    </style>
</head>
<body>
    <div id="draggablediv"></div>
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
    <script>
        $(function () {
            $("#draggablediv").draggable();
        });
    </script>
</body>
</html>

Because of "margin: auto", the draggable element will no longer set the top value accurately. Is there a way to get it to work properly?


Solution

  • Well the issue can be fixed into two steps:

    /* to make sure that both document root & body take the whole vertical space */
    html,body {
      height: 100%;
      display: flex;
      align-items: center;
    }
    
    #draggablediv {
      ... 
      ... 
      /* remove these 2 lines:*/
      top: 0; /* <--- this */
      bottom: 0; /* <--- this */
      ...
    }
    

    This is one of many suggestions, another suggestion (in case you don't want to touch body & document root) you may use another parent div container to apply the same previous rules or to center your element using JQuery also.