[英]How to make fixed element stay within parent's visible borders with CSS?
This is my layout, yellow part is fixed. 这是我的布局,黄色部分固定。 I made a simple script to make the sidebar shrink/grow so that it never goes over the green footer, is it possible to achieve the same with CSS only?
我编写了一个简单的脚本来使边栏缩小/增长,以使其永远不会超出绿色页脚,仅使用CSS就能实现相同的功能吗?
See it in action here: http://jsfiddle.net/RWxGX/203/ 在此处查看其运行情况: http : //jsfiddle.net/RWxGX/203/
I made a simple jquery script so that the fixed yellow sidebar shrinks when the green part goes up when scrolling the window 我制作了一个简单的jquery脚本,以便在滚动窗口时,当绿色部分上升时,固定的黄色侧边栏会缩小
HTML, CSS, JS: HTML,CSS,JS:
<div id="content">
<div id="sidebar">
<div id="sidebar-container">
<div id="sidebar-wrapper">
<div id="sidebar-content">
height: 300px
</div>
</div>
</div>
</div>
<div id="article">
Scroll me to see the sidebar shrink
</div>
</div>
<div id="footer">
</div>
body {
padding: 0;
margin: 0;
min-height: 100%;
}
#content {
display: flex;
justify-content: stretch;
}
#sidebar {
height: inherit;
width: 100px;
flex: 0 0 auto;
background-color: red;
}
#article {
background-color: orange;
flex-grow: 1;
font-size: 55px;
}
#sidebar-container {
position: fixed;
max-height: 100%;
height: inherit;
width: inherit;
background-color: red;
display: flex;
flex-direction: column;
}
#sidebar-wrapper {
background-color: yellow;
overflow-y: scroll;
}
#sidebar-content {
background-color: rgba(255, 0, 0, 0.1);
height: 20000px;
}
#mainbar {
background-color: blue;
}
#content {
height: 300px;
width: 500px;
background-color: rgba(255, 255, 255, 0.75);
}
#footer {
height: 2000px;
width: 500px;
background-color: green;
}
$(document).ready(function() {
var sidebar_container = $('#sidebar-container');
var sidebar_content = $('#sidebar-content');
var footer = $('#footer');
$(window).scroll(function () {
sidebar_container_height =
Math.max(
Math.min(
footer.offset().top - $(window).scrollTop(),
$(window).height()),
0);
sidebar_container.css('height', sidebar_container_height + 'px');
sidebar_content.text('height: ' + sidebar_container_height + 'px');
})
})
I think that in some cases it can be solved using position:absolute;z-index:999
on #footer
. 我认为在某些情况下,可以在
#footer
上使用position:absolute;z-index:999
来#footer
。 But this causes footer to cover sidebar, not to resize sidebar. 但这会导致页脚覆盖侧栏,而不是调整侧栏的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.