让我们说我的网站上有一个与位置相关的元素。在该元素内部,我想要一个固定位置的其他元素。
问题:
在所有浏览器(FF,IE,Opera)和早期的Chrome浏览器中(在Chrome版本26.0.1410上测试),固定元素的位置与父级的相对位置相关。在当前的Chrome浏览器中(在Chrome版本32.0.1700上测试),此固定子项将呈现给父级,而不会考虑其父级相对位置。
CSS
#parent-element{
border: 1px solid red;
height: 100px;
position: relative;
top: 50px;
width: 90%;
}
#child-element{
background-color: yellow;
height: 100px;
width: 100px;
position: fixed;
}
HTML:
<div id="parent-element">
<div id="child-element"></div>
</div>
我当前的解决方案:
现在我发现的最佳解决方案是将父母定位为不是亲戚而是绝对。在这种情况下,父级需要一个容器元素来引用其绝对位置。
CSS:
#parent-container{
position: relative;
height: 100px;
}
#parent-element{
border: 1px solid red;
height: 100px;
position: absolute;
top: 50px;
width: 90%;
}
#child-element{
background-color: yellow;
height: 100px;
width: 100px;
position: fixed;
}
HTML:
<div id="parent-container">
<div id="parent-element">
<div id="child-element"></div>
</div>
</div>
JS Fiddle, my current solution
我不确定这个解决方案在所有情况下都是最好的,如果没有额外的HTML的解决方案能够。因此,如果您有其他解决方案或建议我感兴趣。
出于好奇,有没有人知道为什么Chrome会做出这种改变?
答案 0 :(得分:0)
在我看来,你想要“绝对”位置值而不是“固定”值,不确定为什么/何时发生变化但是根据w3c - 修正:元素相对于浏览器窗口定位。 http://www.w3schools.com/cssref/pr_class_position.asp
#parent-element{
border: 1px solid red;
height: 100px;
position: relative;
top: 50px;
width: 90%;
}
#child-element{
background-color: yellow;
height: 100px;
width: 100px;
position: absolute;
}