position:absolute可拖动div触碰position:relative父元素边缘时缩小问题
解决拖动绝对定位元素时超出父容器自动缩小的问题
问题原因
你在相对定位的父容器内放置绝对定位的可拖动div,拖动到父容器边缘时元素缩小,核心原因是未给可拖动元素设置明确的宽度规则:浏览器会默认根据父容器的可用空间收缩元素宽度,再加上max-width:250px的限制,导致元素超出父容器范围时被挤压变形。
解决方法
给.txtbox添加width: fit-content属性,让元素宽度由自身内容决定,不受父容器可用空间的限制;如果需要固定宽度,直接设置width:250px即可(配合已有的max-width,固定宽度不会超过250px)。
修改后的CSS代码
* { 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; width: fit-content; /* 新增:让宽度由内容自适应,不受父容器限制 */ } .topper { font-size: .625em; border-bottom: 1px solid black; padding: 2px; }
补充说明
- 使用
width: fit-content时,元素宽度会随内容长度自动调整,但不会超过max-width:250px的限制; - 如果需要固定宽度的可拖动元素,将
width: fit-content替换为width:250px即可; - 拖动逻辑无需修改,保持原有JS代码即可。
内容的提问来源于stack exchange,提问作者stackedandcracked
相关产品推荐
相关产品推荐

