Fixed position element inside div container only

南笙酒味 提交于 2020-04-11 04:37:26

问题


I have a fixed block element inside a container. On scrolling the fixed positioned element is going beyond the container. I understood fixed element will be positioned according to window vw. But is there any way to make sure fixed positioned element will get scrolled only upto container position. The fixed position element should not go beyond the container

The problem can be seen in the following.

https://codepen.io/anon/pen/dKLByX

I tried to fix the problem using the following:

if($(window).scrollTop()>1900){
    $('.fixed-ct').css({'bottom':'200px','top':'auto'});
}else if($(document).scrollTop() <=100) {
    $('.fixed-ct').css({'top':'10px','bottom':'auto'});
}else {
    $('.fixed-ct').css({'top':'0px','bottom':'auto'});
}

but sometimes the fixed container is at end because of bottom 200px it should be at top using top:0px on scroll and it should be inside the container itself.


回答1:


There you go, use position sticky inside .fixed-ct and add position:relative to .main-ct

.main-ct {
  width: 1000px;
  height:600px;
  border: 1px solid #000;
  position:relative;
}
.fixed-ct {
  position: sticky;
  width:100px;
  height:20px;
  background: red;
  top:10px;
}
.like-body {
  width: 100%;
  height:1300px;
}
<div class="like-body">
  <div class="main-ct">
    <div class="fixed-ct"></div>
  </div>
</div>


来源:https://stackoverflow.com/questions/51174427/fixed-position-element-inside-div-container-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!