为何left:100%的absolute内层div超出relative父容器?求修复方案
问题原因解释
当绝对定位元素设置left: 100%时,这个百分比是基于父级相对定位容器(红色div)的宽度计算的——它会将元素的左边缘精准对齐到父容器的右边缘。而你的绿色div本身有20px的宽度,所以整个元素自然就完全跑到父容器外部了。
修复方法
以下几种方案都能让绿色div留在红色父容器内:
方案1:结合transform平移
通过transform: translateX(-100%)让元素向左移动自身宽度的100%,这样元素的右边缘会对齐父容器的右边缘:
<div style={{ position: "relative", backgroundColor: "red", width: "100%", height: 100, }} > <div style={{ borderRadius: 10, backgroundColor: "green", height: 20, width: 20, position: "absolute", left: "100%", transform: "translateX(-100%)" }} /> </div>
方案2:使用calc计算left值
直接计算出父容器宽度减去自身宽度的位置作为left值:
<div style={{ position: "relative", backgroundColor: "red", width: "100%", height: 100, }} > <div style={{ borderRadius: 10, backgroundColor: "green", height: 20, width: 20, position: "absolute", left: "calc(100% - 20px)" }} /> </div>
方案3:直接设置right属性
如果不需要基于left定位的逻辑,直接设置right: 0让元素右边缘对齐父容器右边缘:
<div style={{ position: "relative", backgroundColor: "red", width: "100%", height: 100, }} > <div style={{ borderRadius: 10, backgroundColor: "green", height: 20, width: 20, position: "absolute", right: 0 }} /> </div>
内容的提问来源于stack exchange,提问作者peter flanagan
相关产品推荐
相关产品推荐

