如何使设置position:absolute的元素相对于父级div而非body定位
实现方法
绝对定位元素默认相对于最近的position属性非static的祖先元素定位,你当前两个父容器都使用默认的static定位,才会导致绝对定位元素最终参照body定位,只要给对应父容器添加position: relative即可实现需求:
- 要让
box1相对于div_1定位,给.div_1添加position: relative属性 - 要让
box2相对于sub_div定位,给.sub_div添加position: relative属性
修改后完整CSS代码如下:
/*--修改后CSS--*/ .wrapper{ height:80vh; border:1px solid red; } .div_1{ height:70vh; border:1px solid blue; margin:20px; position: relative; /* 新增:作为box1的定位参照 */ } .sub_div{ height:40vh; border:1px solid green; margin:20px; position: relative; /* 新增:作为box2的定位参照 */ } .box{ height:100px; width:100px; background:orange; position:absolute; } .box1{ display:flex; justify-content:center; align-items:center; top:0; left:0; } .box2{ display:flex; justify-content:center; align-items:center; bottom:0; right:0; }
HTML代码无需做任何修改,调整后即可得到你要的效果。
内容的提问来源于stack exchange,提问作者mr.Hritik
相关产品推荐
相关产品推荐

