javascripthtmlcsscss-positionabsolute

draggable position:absolute div shrinking after hitting edge of position:relative div?


I have two draggable divs with position:absolute positioned inside of a position:relative div. My problem is that when I drag my divs to the edge of the position:relative parent they start to shrink. I need my draggable divs to stay the same size when they leave the parent's container, but I have no idea how to fix this issue.

Here's my codepen with the problem

    <div id="all">
        <div class="move txtbox">
            <div class="topper">test test</div>
            <span id="test">test test etst test test test</span>
        </div>
        <div class="move txtbox">
            <div class="topper">test test</div>
            <span id="test">test test etst test test test</span>
        </div>
    </div>
    <script src="move.js"></script>
* {
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
    line-height: 1.1;
    margin: 0;
}

#all {
    position: relative;
    margin: 0 auto;
    width: 50%;
    height: 100vh;
}

.move {
    cursor: move;
    position: absolute;
}

.txtbox, .topper {
    background-color: lightgrey;
}

.txtbox {
    min-height: 70px;
    max-width: 250px;
}

.topper {
    font-size: .625em;
    border-bottom: 1px solid black;
    padding: 2px;
}
const els = document.querySelectorAll(".move");
els.forEach((name) => {
  dragElement(name);
});

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  elmnt.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }
  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = elmnt.offsetTop - pos2 + "px";
    elmnt.style.left = elmnt.offsetLeft - pos1 + "px";
  }
  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

Solution

  • That's totally fine since an absolute positioned element wraps its content according its relative/absolute parent. Just set the width manually:

    elmnt.style.width = elmnt.offsetWidth + 'px';
    

    CODEPEN