简单的问题,难以找到答案.
所以我有3个div.
<div style="position: relative;" class="div-1"> <div style="position: relative;" class="div-2"> <div style="position: absolute;" class="div-3"> Target Div-1's position relative. </div> </div> </div>
第三个div是绝对定位的,但它的目标是直接父:div-2.我希望它以div-1为目标.我怎么能实现这样的呢?
解决方法
MDN’s docs on POSITION声明:
absolute
Do not leave space for the element. Instead,position it at a specified position relative to its closest positioned ancestor or to the containing block. Absolutely positioned Boxes can have margins,they do not collapse with any other margins.
所以,答案并不难找到……在这种结构中无法做到.
<div style="position: relative;" class="div-1"> <div class="div-2"> <div style="position: absolute;" class="div-3"> Target Div-1's position relative. </div> </div> </div>
如果您无法更改HTML,可以使用css类覆盖它:
.div-2 { position: initial !important; }