<分区>
我对固定定位的 div
有问题,它与第二个元素重叠。
如何让fill
元素填充剩余的空间而不被fixed
重叠?
*,
*::before,
*::after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
}
.container {
width: 100%;
height: 100%;
display: flex;
flex-direction: flex-start;
}
.container .fixed {
position: fixed;
width: 100%;
height: 200px;
background: aquamarine;
z-index: 2;
}
.container .fill {
width: 100%;
height: 2500px;
background: orange;
flex: 1;
}
<div class="container">
<div class="fixed">
Fixed content
</div>
<div class="fill">
Remaining space
</div>
</div>
这里正在工作codepen demo
最佳答案
要让您的代码示例正常工作,主要需要做 3 件事:
当使用百分比作为高度时(在 container
上),它的上级也需要一个高度
可选地,可以使用视口(viewport)单位,而不是在 html/body
上添加 height: 100%
,在这种情况下 vh
,并将container
上的height: 100%
改为height: 100vh
使用正确的 flex-direction
值,为此,假设它们应该垂直堆叠,应该是 column
为 fill
元素添加上边距,等于 fixed
元素的高度
堆栈片段
*,
*::before,
*::after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
height: 100%; /* added */
}
.container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column; /* added */
}
.container .fixed {
position: fixed;
left: 0; /* added, some browsers want this too */
top: 0; /* added, some browsers want this too */
width: 100%;
height: 200px;
background: aquamarine;
z-index: 2;
}
.container .fill {
width: 100%;
/*height: 2500px; temp. removed */
background: orange;
flex: 1;
margin-top: 200px; /* added */
}
<div class="container">
<div class="fixed">
Fixed content
</div>
<div class="fill">
Remaining space
</div>
</div>
根据评论/脚本示例更新
如果在fixed
上有一个动态高度,可以使用一个简单的脚本,这里使用 jQuery。
堆栈片段
jQuery(document).ready(function(){
/* get/set margin on page load */
$(".fill").css('margin-top', $(".fixed").height() + 'px')
var btn = $("button");
btn.on("click", function(event){
$(".fixed").append("<div class=\"appended\">Hello</div>");
/* get/set margin */
$(".fill").css('margin-top', $(".fixed").height() + 'px')
});
});
*,
*::before,
*::after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
height: 100%;
}
.container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.container .fixed {
position: fixed;
width: 100%;
background: aquamarine;
z-index: 2;
}
.container .fixed button {
display: block;
padding: 1em;
border-radius: 5px;
box-shadow: none;
border: 0;
background: #d7d7d7;
}
.container .fixed .appended {
padding: 1em;
background: #fff;
border: 1px solid blue;
margin-bottom: 1em;
}
.container .fill {
width: 100%;
background: orange;
flex: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="fixed">
Fixed content
<button>Click to append some element</button>
</div>
<div class="fill">
Remaining space
</div>
</div>
关于html - 使用 flexbox 定位固定 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47903565/