我有一个div,其位置因包含div的相对位置而被抛弃。虽然删除父级的相对位置可以解决问题,但我们宁愿不将其作为解决方案来实现,因为它可能会破坏其他内容。有没有办法强迫孩子忽视其父母的定位?
答案 0 :(得分:12)
不幸的是,没有办法让一个元素“补偿”它的父亲用CSS动态相对定位。除非重新考虑布局,因为position:fixed
不是你所追求的,你的选择是:
position:relative
和与父母完全相反的偏移(您需要再次键入确切的值)。最小的麻烦,但你现在必须记住保持两对偏移(父和子)手动同步。发表评论说“如果你改变它,你也必须改变#THAT”将有所帮助。总而言之,我建议在#2上做#1,并且只有在你无法获得最佳解决方案(更改布局)的时候。
答案 1 :(得分:0)
如果将“relative”更改为“static”不是您的选择...我同意Jon,您必须使用javascript来定位子div,这里是使用javascript执行选项2的代码他的回答是,考虑到所有相对的父母职位,我把孩子移到了一个真实的位置:
var div = document.getElementById("banner");
var parentDiv = document.getElementById("banner");
var posT = 0;
var posL = 0;
while(parentDiv = parentDiv.offsetParent){
posT += parentDiv.offsetTop;
posL += parentDiv.offsetLeft;
}
posT -= div.offsetTop;
posL -= div.offsetLeft;
div.style.top = (-1)*posT+"px";
div.style.left = (-1)*posL+"px";
.corpo{
position:relative;
margin-left:100px;
margin_top:100px;
background-color:yellow;
border:#ccc 1px solid;
padding:10px;
}
#banner{
position:absolute;
top:250px; /* inicial value - goal position considering the document reference */
left:150px; /* inicial value - goal position considering the document reference */
width:50px;
height:50px;
background-color:blue;
font-size:9px;
color:white;
font-family:Arial;
}
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
<div class="corpo">
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx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