我想创建一个位于文本容器左侧的侧边栏,但我不确定我的方法是否可以在浏览器中可靠!
基本上,我依靠一个固定的侧边栏,但避免将left
设置为任何东西,以便它包含在其父级中。
这是一种默认行为还是不同的浏览器以他们自己的小搞笑方式处理的东西?
示例小提琴:https://jsfiddle.net/7enadwus/
示例代码:
<div class="container">
<p>Some text</p>
</div>
<div class="float">
<div class="sidebar">
<p>Sidebar</p>
</div>
</div>
.container {
width: 100%;
height: 600px;
background-color: red;
max-width: 400px;
margin-left: auto;
margin-right: auto;
}
.float {
position: relative;
height: 10px;
width: 100%;
max-width: 800px;
margin-left: auto;
margin-right: auto;
background-color: blue;
}
.sidebar {
position: fixed;
top: 0;
}
这是section 10.3.7 of the spec所涵盖的预期行为。见this answer。固定定位元素计为绝对定位元素,用于这些源的目的。简而言之,left
和right
在未设置时默认为auto,导致固定定位元素保持在其静态位置(未设置position
的位置)。
是的,您可以依赖此行为在所有浏览器中实现互操作。