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

65 Views Asked by At

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?

1

There are 1 best solutions below

0
sohaieb azaiez On BEST ANSWER

Well the issue can be fixed into two steps:

  • To Initially center your element veritically, I would suggest to use FlexBox that way:
/* to make sure that both document root & body take the whole vertical space */
html,body {
  height: 100%;
  display: flex;
  align-items: center;
}
  • To fix the top/bottom wrong offset, you should remove
#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.