我有固定定位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
上)时,它的上升者也需要一个高度
可选地,不是在height: 100%
上添加html/body
,而是可以使用视口单元,在本例中为vh
,并将height: 100%
上的container
更改为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>