如何使用CSS将固定元素保持在父级可见边界内?

时间:2017-09-09 11:56:26

标签: javascript css css3 fixed

这是我的布局,黄色部分是固定的。我制作了一个简单的脚本,使侧边栏缩小/增长,以便它永远不会超过绿色页脚,是否可以通过CSS实现相同的效果?

在此处查看此行动:http://jsfiddle.net/RWxGX/203/

enter image description here

我制作了一个简单的jquery脚本,以便当滚动窗口时绿色部分上升时固定的黄色侧边栏缩小

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');
  })
})

1 个答案:

答案 0 :(得分:0)

我认为在某些情况下可以使用position:absolute;z-index:999上的#footer来解决。但这会导致页脚覆盖侧边栏,而不是调整侧边栏的大小。