我在相对定位的 div 中有一个固定的 div。我希望 div 固定在页面顶部并包含在相对定位的父级中。
此用例的一个常见示例是两列布局中的粘性网站侧边栏。
据我了解。在我的固定 div 上设置 top: 0
会将其固定到顶部。在我的固定 div 上设置 margin-left: 0
会将其与其相对定位的父级对齐。
这在除 Safari(版本 < 10)之外的所有浏览器上都可以正常工作。有没有不涉及用户代理嗅探的方法来解决这个问题。
这是一个最低限度的 fiddle ,说明了下面的隔离问题: http://jsfiddle.net/vgc1ekbg/4/
这是在双栏网站布局的上下文中说明问题的另一个 fiddle :http://jsfiddle.net/dpmj3y0n/1/
最佳答案
根据评论中分享的最后一个 fiddle 进行编辑。
* {
box-sizing: border-box;
}
.wrapper {
max-width: 960px;
height: 2000px;
margin: 0 auto;
text-align: center;
/* line-height: 580px; */
}
.layout {
height: 2000px;
/*padding-left: 20px;*/
/* padding-right: 350px; */
/*margin-right: 192px;*/
}
.layout:before, .layout:after {
content: "";
display: table;
}
.layout:after {
clear: both;
}
.col-main {
width: calc(100% - 184px);
margin-left: -8px;
margin-top: -8px;
height: 580px;
float: left;
position: relative;
left: 200px;
background-color: #f16529;
line-height: 580px;
}
.col-sub {
/* margin-right: -100%; */
position: absolute;
top: 0;
left: 0;
width: 200px;
line-height: 580px;
/* height: 580px; */
background-color: #f0dddd;
float: left;
}
.sticky {
position: fixed;
top: 0;
left: 0;
width: 200px;
height: 100px;
overflow: hidden;
z-index: 100;
background-color: gray;
color: red;
line-height: 100px;
}
<div class="wrapper">
<div class="layout">
<div class="col-main">Main Content</div>
<div class="col-sub">Sidebar Content
<div class="sticky">
Sticky Content
</div>
</div>
</div>
</div>
关于css - 修复了相对父级内的 div 在 Safari 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40917491/